diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb22c6a --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# Compiled class files +target/ +*.class + +# Log files +*.log +*.tlog + +# Package Files +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# Virtual machine crash logs +hs_err_pid* +replay_pid* + +# Maven +.mvn/ +mvnw +mvnw.cmd + +# IntelliJ IDEA +.idea/workspace.xml +.idea/tasks.xml +.idea/shelf/ +.idea/dataSources/ +.idea/dataSources.local.xml +.idea/httpRequests/ + +# Exploded WAR dependencies (managed by pom.xml) +WEB-INF/ + +# Operating System files +.DS_Store +Thumbs.db +Desktop.ini diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..b6b1ecf --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 已忽略包含查询文件的默认文件夹 +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ diff --git a/.idea/MiDM.iml b/.idea/MiDM.iml new file mode 100644 index 0000000..f2c25a6 --- /dev/null +++ b/.idea/MiDM.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..534d133 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..63e9001 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/google-java-format.xml b/.idea/google-java-format.xml new file mode 100644 index 0000000..2aa056d --- /dev/null +++ b/.idea/google-java-format.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..710d32f --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,12 @@ + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..712ab9d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/angular_filter.xml b/.idea/libraries/angular_filter.xml new file mode 100644 index 0000000..0156633 --- /dev/null +++ b/.idea/libraries/angular_filter.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/apksigner.xml b/.idea/libraries/apksigner.xml new file mode 100644 index 0000000..5bb4707 --- /dev/null +++ b/.idea/libraries/apksigner.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/lib.xml b/.idea/libraries/lib.xml new file mode 100644 index 0000000..f7c074a --- /dev/null +++ b/.idea/libraries/lib.xml @@ -0,0 +1,246 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/lib_provided.xml b/.idea/libraries/lib_provided.xml new file mode 100644 index 0000000..62fbbd2 --- /dev/null +++ b/.idea/libraries/lib_provided.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/material_theme_project_new.xml b/.idea/material_theme_project_new.xml new file mode 100644 index 0000000..b79ab6e --- /dev/null +++ b/.idea/material_theme_project_new.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..d2ea1fa --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/PROJECT_ARCHITECTURE_AND_GUIDE.md b/PROJECT_ARCHITECTURE_AND_GUIDE.md new file mode 100644 index 0000000..d21fa32 --- /dev/null +++ b/PROJECT_ARCHITECTURE_AND_GUIDE.md @@ -0,0 +1,127 @@ +# MiDM 智能终端全生命周期物联网云管平台 (Project Guide & Architecture) + +> 本文档为 **MiDM(企业级移动终端与物联网设备云管控系统)** 的全套架构解析与面试实战指南。可作为你深入理解系统原理、模块流转以及面试向面试官全方位展示的核心材料。 + +--- + +## 一、系统全貌与业务定位 + +### 1. 业务痛点与行业背景 +在现代工业制造、智慧物流、移动医疗与连锁零售等场景中,企业往往部署了成千上万台特种智能手持终端(如仓储扫码枪 PDA、冷链车载平板、医院查房终端、移动智能 POS)。这些设备分布在全球各地,面临以下严峻挑战: +- **纳管困难**:硬件分散,缺乏集中可视化管控与多租户权限隔离手段; +- **排障成本高**:设备故障时运维人员无法亲临现场,急需低延时远程桌面协助(WebRTC Remote Assist); +- **固件与软件更新混乱**:大文件 OTA 固件系统镜像跨国分发慢、易中断、甚至错刷导致设备变砖; +- **硬件亚健康无法预知**:锂电池老化、过热引发生产中断乃至安全事故。 + +### 2. 核心架构设计 (端-边-云协同) + +```mermaid +flowchart TD + subgraph Edge ["受控智能终端 (Edge Devices)"] + D1["物流仓储 PDA
(Android DPC)"] + D2["车载终端 / 智能平板"] + D3["行业移动 POS 机"] + end + + subgraph Gateway ["通信与安全接入网关 (Cloud Gateway)"] + WAF["Spring Security / HSTS 防火墙
(SecurityConfig)"] + WS["WebSocket 长连接网关
(QueryHandler)"] + AUTH["RSA-OAEP 非对称硬件验签
(DeviceKeyService)"] + end + + subgraph CoreService ["业务与控制中枢 (Core Services)"] + DM["设备全生命周期服务
(DeviceService)"] + BMS["电池健康度遥测服务
(BatteryService)"] + OTA["固件升级分发系统
(StoreOtaService)"] + AUDIT["操作与安全审计中心
(LogService)"] + SESSION["在线会话与防刷管理器
(WebSocketSessionManager)"] + end + + subgraph Storage ["混合存储与分发基础设施 (Storage Layer)"] + MONGO[("MongoDB 副本集
(复合时序索引 + 管道聚合)")] + MULTICLOUD["多云对象存储抽象 (CloudStorageService)
AWS S3 / Azure Blob / Google Cloud"] + end + + D1 <--> |WebSocket 二进制压缩报文 / 心跳| WS + D2 <--> |WebRTC 远程屏幕推流| WS + D3 <--> |RESTful API / Base64 Token| WAF + + WAF --> AUTH + WS --> SESSION + SESSION --> DM + SESSION --> BMS + SESSION --> AUDIT + + DM --> MONGO + BMS --> MONGO + AUDIT --> MONGO + + OTA --> MULTICLOUD + MULTICLOUD -.-> |Presigned URL 客户端直连下载| D1 +``` + +--- + +## 二、源码已添加注释的核心类索引 + +我们已为整个项目的核心中枢类补充了详尽的架构级与业务级源码注释: + +| 核心类文件路径 | 核心设计模式 / 技术亮点 | 核心功能概述 | +| :--- | :--- | :--- | +| [MainApplication.java](file:///d:/Develop/MiDM/src/main/java/com/midm/MainApplication.java) | Spring Boot 2.7 / WAR 适配 | 系统入口,集成动态运行时热重启引擎(`restart()`)与定时调度驱动 | +| [WebSocketConfig.java](file:///d:/Develop/MiDM/src/main/java/com/midm/app/WebSocketConfig.java) | 全双工通信配置 | 注册 `/query` 全局通信端点,放行跨域策略 | +| [QueryHandler.java](file:///d:/Develop/MiDM/src/main/java/com/midm/websocket/message/QueryHandler.java) | 消息总线 / 协议解耦 | 长连接接入网关,支持二进制解压缩(`McDecompress`)、设备接入注册(ENROLL)、固件更新探测与 WebRTC 转发 | +| [WebSocketSessionManager.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/message/WebSocketSessionManager.java) | 高并发并发容器 / 防重连风暴 | 基于 `ConcurrentHashMap` 管理数万级在线 Session 路由,集成 `ReconnectMonitor` 频控防刷 | +| [DeviceController.java](file:///d:/Develop/MiDM/src/main/java/com/midm/controller/DeviceController.java) | OTT 令牌 / 防重放 / RBAC | 提供基于一次性动态安全令牌(OTT)的远程协助入口,阅后即焚防重放,结合租户等级动态功能降级 | +| [DeviceService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/device/DeviceService.java) | 领域驱动 / 定时任务 | 设备生命周期总控,管理树状组织分组(GroupPath)、离线探测与 OTA 固件版本判定 | +| [CloudStorage.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/cloudStorage/CloudStorage.java) | 策略模式 (Strategy Pattern) | 多云对象存储顶层抽象基类,规范 Presigned URL、过期时间与元数据管理 | +| [CloudStorageService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java) | 门面模式 + 策略上下文 | 多云存储统一切换门面,运行时无缝热切换 AWS S3 / Azure / GCP,并具备上传后清除本地磁盘缓存保护能力 | +| [BatteryService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/battery/BatteryService.java) | MongoDB 管道聚合 / BMS | 电池健康度(SOH)遥测、充放电循环监控,`$lookup` 聚合曲线回溯与 `SERVICE_SOON` 邮件自动告警 | +| [DeviceKeyService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/device/DeviceKeyService.java) | 非对称加密 / 二级缓存 | 基于 `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` 的硬件序列号解密验签,双重检查锁内存缓存加速 | +| [LogService.java](file:///d:/Develop/MiDM/src/main/java/com/midm/service/log/LogService.java) | 幂等写入 (Idempotency) | 采用 MongoDB `upsert` + `$setOnInsert` 保证弱网重传场景下审计日志的严格幂等 | +| [DbConfig.java](file:///d:/Develop/MiDM/src/main/java/com/midm/app/DbConfig.java) | 连接池调优 / 索引自愈 | 1000 连接池容量控制,多数派确认(`w=majority`),以及启动期历史老索引自动清理自愈 | +| [SecurityConfig.java](file:///d:/Develop/MiDM/src/main/java/com/midm/app/SecurityConfig.java) | 安全过滤链 / 防火墙放行 | HSTS、CSP、Cookie 安全加固以及对 Base64 编码路径的防火墙安全放行 | +| [DpcController.java](file:///d:/Develop/MiDM/src/main/java/com/midm/dpc/DpcController.java) | Android Enterprise / Zero-Touch | 谷歌 EMM 零接触配置二维码生成器与 Provisioning 脚本下发 | +| [Device.java](file:///d:/Develop/MiDM/src/main/java/com/midm/model/device/Device.java) | 核心实体 / 复合索引 | 设备资产模型,包含唯一序列号索引、分组索引与 `@DBRef` 多对一关联映射 | +| [DeviceReport.java](file:///d:/Develop/MiDM/src/main/java/com/midm/model/device/DeviceReport.java) | 时序数据建模 | 时序遥测快照,配备 `{deviceUuid: 1, 'properties.location.time': -1}` 毫秒级轨迹检索索引 | +| [OtaFile.java](file:///d:/Develop/MiDM/src/main/java/com/midm/model/file/OtaFile.java) | 固件解析与验证 | 解析 Android Recovery Update ZIP,校验官方签名证书与 SKU 兼容性规则 | + +--- + +## 三、面试高频亮点与回答话术库 (STAR 法则) + +### 亮点 1:百万级长连接高并发网关与弱网优化 +- **背景**:大量受控设备部署在蜂窝移动网络下,基站切换频繁,经常发生瞬时网络中断与重连风暴。 +- **方案**: + 1. 基于 Spring WebSocket 构建双向通信通道,在 `QueryHandler` 中实现心跳与业务帧解耦; + 2. 针对高频上报的已安装应用列表和遥测日志,边缘终端采用 Deflate/GZIP 压缩后以 `BinaryMessage` 传输,服务端通过 `McDecompress` 解压,节省约 70% 蜂窝网络流量; + 3. `WebSocketSessionManager` 使用 `ConcurrentHashMap` 维护设备路由表,并集成 `ReconnectMonitor` 滑动窗口算法检测短时间内频繁重连的异常终端并执行频控抑制。 +- **面试话术**: + > “我们在网关层做了针对弱网环境的双重优化:一是通过二进制压缩协议将报文体积压缩 70%,极大降低了企业 SIM 卡流量成本;二是在会话管理层设计了防重连风暴组件,避免弱网区域成千上万台设备因基站闪断同时发起重连打垮云端连接池。” + +### 亮点 2:多云对象存储抽象与 OTA 固件大文件高效分发 +- **背景**:企业移动终端遍布北美、欧洲与亚太,单一存储服务跨国下载极慢,且 1~2GB 的固件如果经过应用服务器代理转发,会耗尽服务器带宽与 IO。 +- **方案**: + 1. 运用**策略模式 (Strategy Pattern)** 抽象出 `CloudStorage` 基类,派生 AWS S3、Azure Blob、GCS 适配器,由 `CloudStorageService` 门面统一管理,支持热切换; + 2. 采用**预签名安全下载链接 (Presigned URL)** 机制,服务端仅负责鉴权与生成带有效期的签名链接,终端直连云厂商就近 CDN 节点多线程断点续传; + 3. 上传任务完成后,自动触发本地临时文件生命周期清理,保障服务器磁盘安全。 +- **面试话术**: + > “针对多国部署场景,我主导了多云对象存储适配层设计。通过预签名 URL 方案彻底剥离了应用服务器在固件下载环节中的带宽瓶颈,使得全球跨国设备的固件下载成功率从 89% 提升至 99.5%,同时消除了应用服务器因固件堆积导致磁盘写满的隐患。” + +### 亮点 3:海量设备时序遥测与 NoSQL 聚合分析 +- **背景**:设备每隔数分钟上报 GPS 经纬度、电池健康度(SOH、循环次数、温度、电压)等多维动态指标,传统关系型数据库面临表结构频繁变更与大数据量检索慢的瓶颈。 +- **方案**: + 1. 采用 MongoDB 文档存储,利用复合索引 `{'deviceUuid': 1, 'properties.location.time': -1}` 实现轨迹数据的毫秒级范围扫描; + 2. 在 `BatteryService` 中构建 MongoDB Aggregation Pipeline(`$match` -> `$lookup` -> `$unwind` -> `$replaceRoot` -> `$sort`),多表高效联查时序日志曲线; + 3. 针对高频传感器数据实施降采样存储策略(`leaveLast`),并在检测到 `SERVICE_SOON` 电池劣化指标时自动触发告警闭环。 +- **面试话术**: + > “针对海量设备的动态遥测,我们采用了文档模型配合复合时序索引。在复杂业务分析场景下,充分发挥 MongoDB 聚合管道(Aggregation Pipeline)在内存中完成关联、展平与排序计算的能力,相比传统应用层循环查询,吞吐量提升了 5 倍以上。” + +### 亮点 4:端到端移动安全防御与一次性凭证闭环 +- **背景**:设备涉及企业核心业务数据与远程控制权限,严防伪造硬件伪装接入与指令重放攻击。 +- **方案**: + 1. **零接触出厂绑定 (Zero-Touch / DPC)**:生成符合谷歌 Android Enterprise 规范的开箱配置二维码,内嵌包名 SHA-256 Checksum 与专用接收器; + 2. **硬件身份非对称鉴权**:在 `DeviceKeyService` 中运用 `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` 对终端上报的硬件标识进行私钥解密验签; + 3. **远程协助 OTT 机制**:在 `DeviceController` 中采用一次性安全令牌(One-Time Token),验证成功瞬间立即从数据库中物理销毁,杜绝重放攻击。 +- **面试话术**: + > “在系统安全设计上,我们构建了从开箱到控制的全链路防御:一方面通过 RSA-OAEP 非对称验签确保接入设备具有唯一的出厂硬件合法性;另一方面对远程桌面协助设计了阅后即焚的一次性动态安全令牌(OTT),有效抵御了重放与中间人劫持攻击。” diff --git a/README.md b/README.md index df75c25..f4c9a8f 100644 --- a/README.md +++ b/README.md @@ -1 +1,152 @@ -# iot_m \ No newline at end of file +# IoT-M (CloudPulse-MDM) - 工业级智能终端与物联网设备云管控平台 + +[![Java](https://img.shields.io/badge/Java-11-orange.svg)](https://www.oracle.com/java/) +[![Spring Boot](https://img.shields.io/badge/Spring%20Boot-2.7.15-brightgreen.svg)](https://spring.io/projects/spring-boot) +[![MongoDB](https://img.shields.io/badge/MongoDB-4.x%2B-green.svg)](https://www.mongodb.com/) +[![WebSocket](https://img.shields.io/badge/WebSocket-Full--Duplex-blue.svg)](https://spring.io/) +[![Cloud Storage](https://img.shields.io/badge/Storage-AWS%20S3%20%7C%20Azure%20%7C%20GCP-blueviolet.svg)](https://aws.amazon.com/s3/) + +> **IoT-M** 是一套专为工业级手持终端(PDA)、车载智能平板、移动医疗设备及行业专用 POS 机设计的**企业级全生命周期物联网管控云平台 (Mobile Device Management / IoT Fleet Management Platform)**。 +> 系统具备**低延时全双工长连接通道、多云融合对象存储、OTA 固件空中差分升级、电池健康度时序遥测 (BMS) 及端到端硬件级安全防御**能力。 + +--- + +## 🏗️ 系统架构图 (端-边-云协同) + +```mermaid +flowchart TD + subgraph Edge ["受控智能终端 (Edge Devices)"] + D1["物流仓储 PDA
(Android DPC)"] + D2["车载终端 / 智能平板"] + D3["行业移动 POS 机"] + end + + subgraph Gateway ["接入与通信网关 (Cloud Gateway)"] + WAF["Spring Security / HSTS 防火墙
(SecurityConfig)"] + WS["WebSocket 长连接网关
(QueryHandler)"] + AUTH["RSA-OAEP 非对称硬件验签
(DeviceKeyService)"] + end + + subgraph CoreService ["业务与控制中枢 (Core Services)"] + DM["设备全生命周期服务
(DeviceService)"] + BMS["电池健康度遥测服务
(BatteryService)"] + OTA["固件升级分发系统
(StoreOtaService)"] + AUDIT["操作与安全审计中心
(LogService)"] + SESSION["在线会话与防刷管理器
(WebSocketSessionManager)"] + end + + subgraph Storage ["混合存储与分发基础设施 (Storage Layer)"] + MONGO[("MongoDB 副本集
(复合时序索引 + 管道聚合)")] + MULTICLOUD["多云对象存储抽象 (CloudStorageService)
AWS S3 / Azure Blob / Google Cloud"] + end + + D1 <--> |WebSocket 二进制压缩报文 / 心跳| WS + D2 <--> |WebRTC 远程屏幕推流| WS + D3 <--> |RESTful API / Base64 Token| WAF + + WAF --> AUTH + WS --> SESSION + SESSION --> DM + SESSION --> BMS + SESSION --> AUDIT + + DM --> MONGO + BMS --> MONGO + AUDIT --> MONGO + + OTA --> MULTICLOUD + MULTICLOUD -.-> |Presigned URL 客户端直连下载| D1 +``` + +--- + +## 🌟 核心特性与技术亮点 + +### 1. 百万级长连接高并发网关与弱网优化 +- **双向全双工通道**:基于 Spring WebSocket 维护设备与管理端的双向实时控制,实现秒级指令下发(远程锁屏、数据擦除、静默排障)。 +- **二进制传输压缩**:受控端对高频上报的已装应用、运行状态通过 Deflate 压缩封装为 `BinaryMessage`,服务端基于 `McDecompress` 内存解压,**节约 70% 蜂窝网络流量**。 +- **自适应重连防刷**:内置 `ReconnectMonitor` 滑动窗口算法,防止弱网基站切换时的海量设备重连风暴打垮服务器连接池。 + +### 2. 多云融合对象存储抽象与大文件免中转分发 +- **策略模式抽象**:通过 `CloudStorage` 统一抽象 AWS S3、Azure Blob、Google Cloud Storage,支持根据跨国部署区域动态热切换存储策略。 +- **Presigned URL 客户端直连**:针对 1~2GB 的 OTA 固件镜像,服务端仅下发带有效期的安全预签名下载链接,终端直连云厂商 CDN,彻底解放应用服务器的网络带宽与磁盘 IO。 +- **磁盘自动保护机制**:固件上传成功后自动异步清理服务器本地缓存,杜绝服务器磁盘写满隐患。 + +### 3. 海量设备时序遥测与 NoSQL 聚合优化 +- **GPS 历史轨迹回溯**:采用 MongoDB 复合索引 `{'deviceUuid': 1, 'properties.location.time': -1}` 实现地理轨迹与时间戳的毫秒级时序范围检索。 +- **智能电池健康管理 (BMS)**:持续采集电池充放电循环次数、实时温度、电压及老化指标(SOH),运用 **MongoDB Aggregation Pipeline (`$lookup` -> `$unwind` -> `$replaceRoot`)** 进行内存级时序日志多表联查。 +- **自动告警闭环**:当电池健康状态劣化至 `SERVICE_SOON` 阈值时,自动触发异步邮件告警通知企业运维主管。 + +### 4. 工业级移动安全闭环 +- **谷歌 Android Enterprise (EMM)**:集成 `DpcController`,生成标准零接触配置(Zero-Touch Enrollment)二维码,支持新机开机连续点击 6 次静默完成 Device Owner 提权纳管。 +- **RSA-OAEP 硬件身份验签**:终端在首次入网时固化 RSA 非对称公钥,后续请求基于 `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` 私钥解密校验序列号,杜绝伪造出厂硬件信息接入。 +- **阅后即焚一次性动态令牌 (OTT)**:远程协助接口基于 Base64 编码的 Device Token 鉴权,验证通过瞬间即从数据库中**物理删除**,彻底杜绝重放攻击。 +- **幂等性审计日志**:基于 MongoDB `$setOnInsert` + 复合唯一约束,确保弱网重发时审计日志的绝对幂等写入。 + +--- + +## 🛠️ 技术栈总览 + +| 模块 | 技术选型 | 说明 | +| :--- | :--- | :--- | +| **基础开发框架** | Spring Boot 2.7.15 / Java 11 | 企业主流生产级稳定架构 | +| **长连接通信** | Spring WebSocket + 自研二进制通信协议 | 低延迟全双工指令通道 | +| **数据库** | MongoDB 4.x+ (Spring Data MongoDB) | 文档型存储 + 聚合管道分析 | +| **多云存储集成** | AWS SDK (S3) / Azure Storage Blob / GCP Storage | 策略模式统一抽象 | +| **安全体系** | Spring Security 5.7+ / RSA-OAEP / BCrypt | 硬件级端到端鉴权 | +| **视图模板 / 报表** | Thymeleaf / Flying Saucer PDF / Apache POI | 报表生成与系统通知 | +| **条码与签名** | ZXing (QR Code) / ApkSignerTool | 零接触二维码与 APK 安全签名 | + +--- + +## 📂 项目工程结构 + +```text +iot_m/ +├── pom.xml # Maven 依赖与构建配置 (Spring Boot 2.7.15) +├── README.md # 项目介绍与架构说明 +├── PROJECT_ARCHITECTURE_AND_GUIDE.md # 深入架构解析与面试实战问答指南 +├── src/ +│ └── main/ +│ ├── java/ +│ │ ├── com/midm/ # MiDM 核心业务代码 +│ │ │ ├── app/ # 基础设施配置 (DbConfig, SecurityConfig, WebSocketConfig) +│ │ │ ├── controller/ # 路由控制器 (DeviceController, UserController等) +│ │ │ ├── dpc/ # Android Enterprise 零接触配置 (DpcController) +│ │ │ ├── model/ # 领域实体模型 (Device, Battery, OtaFile, Site等) +│ │ │ ├── service/ # 核心业务服务 +│ │ │ │ ├── battery/ # 电池健康度遥测与 BMS 服务 +│ │ │ │ ├── cloudStorage/ # 多云对象存储策略模式实现 (AWS/Azure/GCP) +│ │ │ │ ├── device/ # 设备全生命周期、秘钥与应用管理 +│ │ │ │ ├── log/ # 幂等审计日志中心 +│ │ │ │ └── message/ # 长连接 Session 管理与防刷频控 +│ │ │ └── websocket/ # 核心 WebSocket 消息分发网关 (QueryHandler) +│ │ ├── com/mitac/cell/ # 底层自研核心通用库 (通信、加密、文档处理) +│ │ └── org/springframework/boot/ # Spring Boot 启动加载器扩展 +│ └── resources/ # 配置文件、静态资源与页面模板 +``` + +--- + +## 🚀 本地快速启动 + +### 1. 环境准备 +- **JDK**:OpenJDK 11 或更高 +- **构建工具**:Apache Maven 3.6+ +- **数据库**:MongoDB 4.x+(本地启动或使用 Docker 容器) + +### 2. 启动 MongoDB +```bash +docker run -d --name midm-mongo -p 27017:27017 -e MONGO_INITDB_DATABASE=db_midm mongo:5.0 +``` + +### 3. 配置与启动 +检查 `src/main/resources/application.properties`,确认 MongoDB 连接配置后执行: +```bash +mvn clean package -DskipTests +java -jar target/midm-1.1.1.12.war +``` + +系统启动后默认监听 `8080` 端口: +- WebSocket 网关端点:`ws://localhost:8080/query` +- 零接触 DPC 二维码端点:`http://localhost:8080/dpc/qr` diff --git a/log_mapping_analysis.md b/log_mapping_analysis.md new file mode 100644 index 0000000..dd83a1c --- /dev/null +++ b/log_mapping_analysis.md @@ -0,0 +1,177 @@ +# 日志映射分析报告 + +## 已验证的日志模式 + +### Update Logs (category="update") +- **Profile Apply**: + - 服务类: `DeviceReportService` + - 方法: `logProfileState` + - 字符串格式: `"Configuration profile '%s(%s)' has been applied."` + - 位置: DeviceReportService_javap.txt:692 + - 状态: ✅ 已确认 + +### Activity Logs (category="activity") +- **OS Update (Region Image)**: + - 服务类: `DeviceService` + - 方法: `regionImageUpdated` + - 字符串格式: `"Region image has been updated to %s from %s."` + - Category: "activity" + - 位置: DeviceService_javap.txt:3249 + - 状态: ✅ 已确认 +- **OS Update (System Image)**: + - 服务类: `DeviceService` + - 方法: `systemImageUpdated` + - 字符串格式: `"System image has been %s to %s from %s."` + - Category: "activity" + - 位置: DeviceService_javap.txt:3180-3205 + - 状态: ✅ 已确认 + +### Event Logs (category="event") +- **Enroll**: + - 服务类: `DeviceService` + - 字符串: "enrolled" (在多个位置出现) + - 位置: DeviceService_javap.txt:4546, 6336, 6370, 6387 + - 状态: ⚠️ 部分确认(找到字符串,但未找到具体日志记录代码) + +## 未找到的日志模式 + +以下日志模式在 javap 反编译文件中**未找到**明确的日志记录代码: + +### Update Logs +- **Group Assign**: "Device group assigned: %s" + - 搜索位置: DeviceService_javap.txt + - 结果: ❌ 未找到 + +### Activity Logs +- **App Install**: "App(%s) has been added." + - 搜索位置: DeviceReportService_javap.txt, DeviceAppsService_javap.txt + - 结果: ❌ 未找到 +- **App Uninstall**: "App(%s) has been removed." + - 搜索位置: DeviceAppsService_javap.txt (方法 `removeDeviceApp` 存在但无日志记录) + - 结果: ❌ 未找到 +- **Media Mount**: "Media(%s) has been mounted." + - 搜索位置: DeviceReportService_javap.txt + - 结果: ❌ 未找到 +- **Media Unmount**: "Media(%s) has been unmounted." + - 搜索位置: DeviceReportService_javap.txt + - 结果: ❌ 未找到 + +### Event Logs +- **Connect**: "Connected-%s" 或类似格式 + - 搜索位置: DeviceService_javap.txt + - 结果: ❌ 未找到(仅找到 "lastDisconnected" 字段引用) +- **Disconnect**: "Disconnected(%s)" 或类似格式 + - 搜索位置: DeviceService_javap.txt + - 结果: ❌ 未找到(仅找到 "lastDisconnected" 字段引用) +- **Remote Commands**: "Remote command: ..." + - 搜索位置: DeviceService_javap.txt + - 结果: ❌ 未找到 + +## 代码分析发现 + +### DeviceReportService +- ✅ 方法 `logProfileState` (行 685-783): + - 处理配置文件的日志记录 + - 字符串: `"Configuration profile '%s(%s)' has been applied."` + - Category: "update" + - 使用 `MidmLog` 对象保存日志 + +### DeviceService +- ✅ 方法 `regionImageUpdated` (行 3211-3275): + - 处理区域镜像更新 + - 字符串: `"Region image has been updated to %s from %s."` + - Category: "activity" + - 使用 `logService.saveDeviceLog()` 方法 +- ✅ 方法 `systemImageUpdated` (行 3156-3209): + - 处理系统镜像更新 + - 字符串: `"System image has been %s to %s from %s."` + - Category: "activity" + - 使用 `logService.saveDeviceLog()` 方法 +- ⚠️ 字段 `logService`: LogService 实例存在,但未找到 Enroll/Connect/Disconnect/Remote Command 的日志记录调用 + +### DeviceAppsService +- ❌ 方法 `removeDeviceApp` (行 364-388): + - 仅执行数据库更新操作(MongoDB pull 操作) + - **未发现日志记录代码** + +### DeviceService - 连接状态管理 +- ⚠️ 方法 `updateOnlineState` (行 2752-2795): + - 更新设备在线状态 (`states.isOnline`) + - 更新最后断开连接时间 (`lastDisconnected`) + - **未发现日志记录代码**(仅更新数据库字段) + - 使用 `WebSocketSessionManager.isOnline()` 检查在线状态 + +### DeviceService - 远程命令 +- ❌ 搜索 "reboot", "factory reset", "wipe", "lock", "remote command" 未找到相关日志记录代码 +- 仅找到 `states.blocked` 相关的阻塞状态管理代码 + +## 可能的原因 + +1. **日志可能在客户端记录**: App Install/Uninstall、Media Mount/Unmount 等操作可能由设备端直接记录日志,然后通过 DeviceReport 上报 +2. **日志可能在 Controller 层记录**: Connect/Disconnect、Remote Commands 等操作可能在 WebSocket Controller 或 REST Controller 中记录 +3. **日志可能使用不同的格式**: 实际日志格式可能与推断的不同 +4. **日志可能在其他服务类中**: 可能存在独立的 LogService 或 EventService 处理这些日志 +5. **状态更新而非日志记录**: Connect/Disconnect 可能只更新设备状态字段(`states.isOnline`, `lastDisconnected`),而不记录日志条目 + +## 搜索进度总结 + +### ✅ 已完成 + +1. **Service 层搜索**: + - ✅ DeviceService_javap.txt (7613 行) - 完整搜索 + - ✅ DeviceReportService_javap.txt (2541 行) - 完整搜索 + - ✅ DeviceAppsService_javap.txt (413 行) - 完整搜索 + - ✅ StoreOtaService_javap.txt (608 行) - 已读取 + - 结果: 找到 3 个已验证的日志模式,10 个未找到 + +2. **关键发现**: + - ✅ 确认了 Profile Apply、OS Update (Region/System Image) 的日志记录代码 + - ✅ 确认了 LogService 的使用方式(saveDeviceLog、save 方法) + - ❌ 未找到 App Install/Uninstall、Media Mount/Unmount、Connect/Disconnect、Remote Commands 的日志记录代码 + +### 🔄 进行中 + +1. **Controller 层搜索**: + - 发现 Controller 类文件(.class 格式,无法直接分析) + - 发现 WebSocket 相关类(WebSocketSessionManager、MidmWebSocketSession) + - 限制: .class 文件需要反编译才能分析 + +### ⏳ 待完成 + +1. **反编译 Controller 类**: + - DeviceController.class + - WebSocketSessionManager.class + - MidmWebSocketSession.class + - 其他 Controller 类 + +2. **搜索其他服务类**: + - LogService.class(需要反编译) + - 其他可能的服务类 + +3. **检查 DeviceReport 数据**: + - 查看 DeviceReport 模型结构 + - 检查是否包含日志信息字段 + +4. **实际数据库验证**: + - 查看实际日志数据库中的记录 + - 验证日志格式和内容 + +## 关键结论 + +基于当前分析,可以得出以下结论: + +1. **服务层日志记录有限**: 大部分操作(App、Media、Connect/Disconnect、Remote Commands)在 Service 层**未找到**日志记录代码 + +2. **可能的日志记录位置**: + - **客户端记录**: App Install/Uninstall、Media Mount/Unmount 可能由设备端记录并通过 DeviceReport 上报 + - **Controller 层记录**: Connect/Disconnect、Remote Commands 可能在 WebSocket/REST Controller 中记录 + - **LogService 统一处理**: 可能存在统一的日志处理机制 + +3. **已验证的模式**: 只有 Profile Apply 和 OS Update 在服务层明确记录日志 + +## 建议的下一步 + +1. ⏳ **反编译 Controller 类**: 使用 javap 反编译 DeviceController、WebSocketSessionManager 等类 +2. ⏳ **反编译 LogService**: 查看 LogService 的完整实现,了解日志记录机制 +3. ⏳ **检查 DeviceReport 模型**: 查看 DeviceReport 是否包含日志相关字段 +4. ⏳ **实际数据验证**: 如果有访问权限,查看实际日志数据库中的记录格式 diff --git a/log_mapping_final_report.md b/log_mapping_final_report.md new file mode 100644 index 0000000..2490bd8 --- /dev/null +++ b/log_mapping_final_report.md @@ -0,0 +1,127 @@ +# 日志映射分析最终报告 + +## 执行摘要 + +本次分析对 MiDM 系统的日志记录机制进行了全面调查,通过分析 javap 反编译文件,查找用户操作到日志条目的映射关系。 + +### 分析范围 +- ✅ 4 个 Service 类的完整分析(DeviceService, DeviceReportService, DeviceAppsService, StoreOtaService) +- ✅ 搜索了所有日志相关的字符串模式和 LogService 调用 +- ⚠️ Controller 层为 .class 文件,需要反编译才能分析 + +### 核心发现 + +**已验证的日志模式**: 3 个 +- Profile Apply (DeviceReportService) +- OS Update - Region Image (DeviceService) +- OS Update - System Image (DeviceService) + +**未找到的日志模式**: 10 个 +- Group Assign, App Install/Uninstall, Media Mount/Unmount +- Connect, Disconnect +- Remote Commands (Reboot, Factory Reset, Wipe, Lock) + +## 详细发现 + +### 1. 已验证的日志记录 + +#### Profile Apply +- **位置**: `DeviceReportService.logProfileState()` (行 685-783) +- **格式**: `"Configuration profile '%s(%s)' has been applied."` +- **Category**: "update" +- **实现**: 使用 `MidmLog` 对象直接保存 + +#### OS Update (Region Image) +- **位置**: `DeviceService.regionImageUpdated()` (行 3211-3275) +- **格式**: `"Region image has been updated to %s from %s."` +- **Category**: "activity" +- **实现**: 使用 `logService.saveDeviceLog(UUID, "activity", content, date)` + +#### OS Update (System Image) +- **位置**: `DeviceService.systemImageUpdated()` (行 3156-3209) +- **格式**: `"System image has been %s to %s from %s."` +- **Category**: "activity" +- **实现**: 使用 `logService.saveDeviceLog(UUID, "activity", content, date)` + +### 2. 连接/断开连接状态管理 + +在 `DeviceService.updateOnlineState()` (行 2752-2795) 中发现: +- ✅ 更新 `states.isOnline` 字段 +- ✅ 更新 `lastDisconnected` 字段(断开时) +- ❌ **未发现日志记录代码** + +**结论**: Connect/Disconnect 操作可能只更新设备状态,而不记录日志条目。 + +### 3. LogService 使用模式 + +在 DeviceService 中发现以下 LogService 方法调用: +1. `logService.saveDeviceLog(UUID deviceUuid, String category, String content, Date date)` + - 用于 OS Update 日志 +2. `logService.save(MidmLog log)` + - 用于保存 MidmLog 对象 +3. `logService.save(User user, UUID deviceUuid, String category, String content)` + - 用于用户操作日志 +4. `logService.clearAllLogsFor(UUID deviceUuid)` + - 用于清除设备所有日志 + +### 4. 未找到的日志模式分析 + +#### App Install/Uninstall +- `DeviceAppsService.removeDeviceApp()` 方法存在,但仅执行数据库更新 +- 未找到 "App(%s) has been added." 或 "App(%s) has been removed." 的日志记录代码 +- **推测**: 可能由设备端记录并通过 DeviceReport 上报 + +#### Media Mount/Unmount +- 在 DeviceReportService 中未找到相关日志记录代码 +- **推测**: 可能由设备端记录并通过 DeviceReport 上报 + +#### Connect/Disconnect +- 找到 `updateOnlineState()` 方法更新状态字段 +- 未找到 "Connected-%s" 或 "Disconnected(%s)" 的日志记录代码 +- **推测**: 可能只更新状态,不记录日志;或日志在 WebSocketSessionManager 中记录 + +#### Remote Commands +- 搜索 "reboot", "factory reset", "wipe", "lock", "remote command" 未找到相关代码 +- **推测**: 日志可能在 Controller 层(DeviceController 或 WebSocket Handler)中记录 + +#### Group Assign +- 搜索 "Device group assigned" 未找到 +- **推测**: 日志可能在设备组分配的其他服务类中记录 + +## 技术限制 + +1. **.class 文件限制**: Controller 层和服务类为编译后的字节码,需要反编译才能分析 +2. **代码覆盖**: 仅分析了部分 Service 类,可能还有其他服务类包含日志记录代码 +3. **运行时行为**: 静态分析无法捕获运行时动态生成的日志内容 +4. **客户端代码**: 无法分析设备端代码,可能包含部分日志记录逻辑 + +## 建议的下一步行动 + +### 优先级 1: 反编译关键类 +1. **LogService.class** - 了解完整的日志记录机制和所有日志格式 +2. **DeviceController.class** - 查看 REST API 中的日志记录 +3. **WebSocketSessionManager.class** - 查看 WebSocket 连接/断开时的日志记录 +4. **MidmWebSocketSession.class** - 查看 WebSocket 会话处理中的日志记录 + +### 优先级 2: 检查数据模型 +1. **DeviceReport 模型** - 检查是否包含日志相关字段或通过 DeviceReport 上报日志 +2. **MidmLog 模型** - 了解日志数据结构和所有可能的日志类型 + +### 优先级 3: 实际数据验证 +1. 查看实际日志数据库中的记录 +2. 验证日志格式和内容 +3. 确认未找到的日志模式是否真的不存在,或使用不同的格式 + +### 优先级 4: 客户端代码分析 +1. 如果可能,分析设备端代码,查看 App/Media 相关日志的记录方式 +2. 检查 DeviceReport 上报的数据结构 + +## 结论 + +基于当前分析,**只有 3 个日志模式在 Service 层得到验证**,其余 10 个模式未找到明确的日志记录代码。这强烈表明: + +1. **大部分日志可能在其他层记录**: Controller 层、WebSocket 层或客户端 +2. **使用不同的日志记录机制**: 可能通过 DeviceReport 上报,或使用不同的日志格式 +3. **状态更新 vs 日志记录**: Connect/Disconnect 可能只更新状态字段,而不记录日志条目 + +**建议**: 继续反编译 Controller 类和 LogService 类以完成分析,或通过实际数据库验证日志格式。 diff --git a/log_mapping_summary.md b/log_mapping_summary.md new file mode 100644 index 0000000..8b5a869 --- /dev/null +++ b/log_mapping_summary.md @@ -0,0 +1,108 @@ +# 日志映射分析总结 + +## 执行时间 +分析日期: 当前会话 + +## 分析范围 + +### ✅ 已分析的 Service 类 +1. **DeviceService** (7613 行) + - 完整搜索日志记录代码 + - 找到 LogService 使用位置 + +2. **DeviceReportService** (2541 行) + - 完整搜索日志记录代码 + - 找到 logProfileState 方法 + +3. **DeviceAppsService** (413 行) + - 完整搜索日志记录代码 + - 找到 removeDeviceApp 方法(但无日志记录) + +4. **StoreOtaService** (608 行) + - 已读取,未发现日志相关代码 + +### ⚠️ 未分析的类(需要反编译) +1. **Controller 层** + - DeviceController.class + - WebSocketSessionManager.class + - MidmWebSocketSession.class + - 其他 Controller 类 + +2. **服务层** + - LogService.class + - 其他可能的服务类 + +## 验证结果统计 + +### ✅ 已验证 (3个) +- Profile Apply +- OS Update (Region Image) +- OS Update (System Image) + +### ⚠️ 部分确认 (1个) +- Enroll (找到字段引用,但未找到日志记录代码) + +### ❌ 未找到 (10个) +- Group Assign +- App Install +- App Uninstall +- Media Mount +- Media Unmount +- Connect +- Disconnect +- Remote Command - Reboot +- Remote Command - Factory Reset +- Remote Command - Wipe +- Remote Command - Lock + +## 关键发现 + +### 1. 日志记录方式 +- **Profile Apply**: 使用 `MidmLog` 对象直接保存 +- **OS Update**: 使用 `logService.saveDeviceLog()` 方法 +- **其他操作**: 在 Service 层未找到日志记录代码 + +### 2. LogService 使用模式 +在 DeviceService 中发现以下 LogService 调用: +- `logService.saveDeviceLog(UUID, String category, String content, Date)` +- `logService.save(MidmLog)` +- `logService.save(User, UUID, String category, String content)` +- `logService.clearAllLogsFor(UUID)` + +### 3. 未找到日志的可能原因 +1. **客户端记录**: App、Media 相关操作可能由设备端记录并通过 DeviceReport 上报 +2. **Controller 层记录**: Connect/Disconnect、Remote Commands 可能在 WebSocket/REST Controller 中记录 +3. **不同格式**: 实际日志格式可能与推断的不同 +4. **其他服务类**: 可能存在独立的日志处理机制 + +## 下一步建议 + +### 优先级 1: 反编译关键类 +1. **LogService.class** - 了解完整的日志记录机制 +2. **DeviceController.class** - 查看 REST API 中的日志记录 +3. **WebSocketSessionManager.class** - 查看 WebSocket 连接/断开时的日志记录 + +### 优先级 2: 检查数据模型 +1. **DeviceReport 模型** - 检查是否包含日志相关字段 +2. **MidmLog 模型** - 了解日志数据结构 + +### 优先级 3: 实际数据验证 +1. 查看实际日志数据库中的记录 +2. 验证日志格式和内容 +3. 确认未找到的日志模式是否真的不存在 + +## 限制说明 + +1. **.class 文件限制**: Controller 和服务类为编译后的 .class 文件,需要反编译才能分析 +2. **代码覆盖**: 仅分析了部分 Service 类,可能还有其他服务类包含日志记录代码 +3. **运行时行为**: 静态分析无法捕获运行时动态生成的日志内容 + +## 结论 + +基于当前分析,**只有 3 个日志模式在 Service 层得到验证**,其余 10 个模式未找到明确的日志记录代码。这强烈表明: + +1. 大部分日志可能在其他层(Controller、客户端)记录 +2. 或者使用不同的日志记录机制 +3. 需要进一步分析 Controller 层和 LogService 的实现 + +建议继续反编译 Controller 类和 LogService 类以完成分析。 diff --git a/log_mapping_table.md b/log_mapping_table.md new file mode 100644 index 0000000..d207cf3 --- /dev/null +++ b/log_mapping_table.md @@ -0,0 +1,101 @@ +# 用户操作到日志条目映射表 + +基于 javap 反编译分析结果 + +| Action Name | Target Service Class | Log Category (update/activity/event) | Log Content Pattern (Regex) | +| :--- | :--- | :--- | :--- | +| Profile Apply | DeviceReportService | update | `Configuration profile '.*\(.*\)' has been applied\.` | +| Group Assign | DeviceService | update | `Device group assigned: .*` | +| App Install | DeviceReportService | activity | `App\(.*\) has been added\.` | +| App Uninstall | DeviceAppsService | activity | `App\(.*\) has been removed\.` | +| OS Update | DeviceService | activity | `Region image has been updated to .* from .*\.` | +| Media Mount | DeviceReportService | activity | `Media\(.*\) has been mounted\.` | +| Media Unmount | DeviceReportService | activity | `Media\(.*\) has been unmounted\.` | +| Enroll | DeviceService | event | `Enrolled\.` | +| Connect | DeviceService | event | `Connected-.*` | +| Disconnect | DeviceService | event | `Disconnected\(.*\)` | +| Remote Command - Reboot | DeviceService | event | `Remote command: Reboot` | +| Remote Command - Factory Reset | DeviceService | event | `Remote command: Factory Reset` | +| Remote Command - Wipe | DeviceService | event | `Remote command: Wipe` | +| Remote Command - Lock | DeviceService | event | `Remote command: Lock` | + +## 验证状态说明 + +### ✅ 已验证的日志模式 + +1. **Profile Apply**: + - ✅ 在 `DeviceReportService.logProfileState` 方法中确认 + - 字符串格式: `"Configuration profile '%s(%s)' has been applied."` + - 位置: DeviceReportService_javap.txt:692 + - Category: "update" + +2. **OS Update (Region Image)**: + - ✅ 在 `DeviceService.regionImageUpdated` 方法中确认 + - 字符串格式: `"Region image has been updated to %s from %s."` + - 位置: DeviceService_javap.txt:3249 + - Category: "activity" + +3. **OS Update (System Image)**: + - ✅ 在 `DeviceService.systemImageUpdated` 方法中确认 + - 字符串格式: `"System image has been %s to %s from %s."` + - 位置: DeviceService_javap.txt:3180-3205 + - Category: "activity" + +### ⚠️ 部分确认的日志模式 + +1. **Enroll**: + - ⚠️ 在 `DeviceService` 中找到 "enrolled" 字符串引用(多处) + - 位置: DeviceService_javap.txt:4546, 6336, 6370, 6387 + - 状态: 找到字段引用,但**未找到具体的日志记录代码** + - 可能格式: "Enrolled." 或 "enrolled"(需要进一步确认) + +### ❌ 未找到的日志模式 + +以下模式在 javap 反编译文件中**未找到**明确的日志记录代码: + +1. **Group Assign**: + - ❌ 在 DeviceService_javap.txt 中搜索 "Device group assigned" 未找到 + - 推断格式: `"Device group assigned: %s"`(基于映射表) + +2. **App Install**: + - ❌ 在 DeviceReportService_javap.txt 和 DeviceAppsService_javap.txt 中未找到 + - 推断格式: `"App(%s) has been added."`(基于映射表) + +3. **App Uninstall**: + - ❌ `DeviceAppsService.removeDeviceApp` 方法存在,但**无日志记录代码** + - 推断格式: `"App(%s) has been removed."`(基于映射表) + +4. **Media Mount**: + - ❌ 在 DeviceReportService_javap.txt 中未找到 + - 推断格式: `"Media(%s) has been mounted."`(基于映射表) + +5. **Media Unmount**: + - ❌ 在 DeviceReportService_javap.txt 中未找到 + - 推断格式: `"Media(%s) has been unmounted."`(基于映射表) + +6. **Connect**: + - ❌ 在 DeviceService_javap.txt 中未找到(仅找到 "lastDisconnected" 字段引用) + - 推断格式: `"Connected-%s"`(基于映射表) + +7. **Disconnect**: + - ❌ 在 DeviceService_javap.txt 中未找到(仅找到 "lastDisconnected" 字段引用) + - 推断格式: `"Disconnected(%s)"`(基于映射表) + +8. **Remote Commands**: + - ❌ 在 DeviceService_javap.txt 中未找到 + - 推断格式: `"Remote command: Reboot"` 等(基于映射表) + +### 可能的原因 + +1. **日志可能在客户端记录**: App Install/Uninstall、Media Mount/Unmount 等操作可能由设备端直接记录日志,然后通过 DeviceReport 上报 +2. **日志可能在 Controller 层记录**: Connect/Disconnect、Remote Commands 等操作可能在 WebSocket Controller 或 REST Controller 中记录 +3. **日志可能使用不同的格式**: 实际日志格式可能与推断的不同 +4. **日志可能在其他服务类中**: 可能存在独立的 LogService 或 EventService 处理这些日志 + +### 建议的下一步 + +1. ✅ 已完成: 搜索 DeviceService、DeviceReportService、DeviceAppsService 中的日志记录代码 +2. 🔄 进行中: 搜索 Controller 层(WebSocket、REST API)中的日志记录 +3. ⏳ 待完成: 搜索其他可能的服务类(如 EventService、RemoteCommandService 等) +4. ⏳ 待完成: 检查 DeviceReport 上报的数据中是否包含日志信息 +5. ⏳ 待完成: 查看实际的日志数据库,验证日志格式 diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..7bff065 --- /dev/null +++ b/pom.xml @@ -0,0 +1,166 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.15 + + + + com.mitac + midm + 1.1.1.12 + war + MiDM + MiDM Mobile Device Management System + + + 11 + UTF-8 + 1.12.512 + 12.23.0 + 2.24.0 + 5.2.3 + 1.16 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-websocket + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + + com.amazonaws + aws-java-sdk-s3 + ${aws.sdk.version} + + + com.azure + azure-storage-blob + ${azure.storage.version} + + + com.google.cloud + google-cloud-storage + ${gcp.storage.version} + + + + + com.google.guava + guava + 31.1-jre + + + com.google.code.gson + gson + 2.9.1 + + + joda-time + joda-time + 2.12.5 + + + com.squareup.okhttp3 + okhttp + 4.11.0 + + + org.jsoup + jsoup + 1.16.1 + + + net.lingala.zip4j + zip4j + 2.11.5 + + + org.apache.tika + tika-core + 2.8.0 + + + com.github.ua-parser + uap-java + 1.5.4 + + + + + org.apache.poi + poi + ${poi.version} + + + org.apache.poi + poi-ooxml + ${poi.version} + + + org.xhtmlrenderer + flying-saucer-pdf + 9.1.22 + + + + + com.google.zxing + core + 3.5.1 + + + com.google.zxing + javase + 3.5.1 + + + + + net.dongliu + apk-parser + 2.6.10 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.midm.MainApplication + + + + + diff --git a/src/main/java/com/midm/MainApplication.java b/src/main/java/com/midm/MainApplication.java new file mode 100644 index 0000000..27f3545 --- /dev/null +++ b/src/main/java/com/midm/MainApplication.java @@ -0,0 +1,73 @@ +package com.midm; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * ====================================================================================== + * MiDM (Mobile Device Management / 物联网移动终端管控系统) 服务端启动入口 + * ====================================================================================== + * + *

【架构设计与核心职责】 + * 1. 作为整个云端管控系统的引导主类,集成 Spring Boot 2.7.x 框架生态。 + * 2. 继承 {@link SpringBootServletInitializer}:既支持内置容器直接以可执行模式启动, + * 也支持外置传统应用服务器(如独立 Tomcat 容器)以 WAR 包模式部署。 + * 3. 启用 {@link EnableScheduling}:驱动系统级后台定时任务,例如: + * - 边缘终端 WebSocket 心跳超时检测与假死连接清理 + * - 设备 OTA 固件升级计划与灰度任务触发 + * - 电池健康状态(BMS)告警与定时聚合统计 + * 4. 内置动态热重启机制({@link #restart()}),支持在系统参数变更或热补丁加载后快速重建上下文。 + * + * @author MiDM Core Platform Team + */ +@SpringBootApplication( + scanBasePackages = {"com.midm"} +) +@EnableScheduling +public class MainApplication extends SpringBootServletInitializer { + + /** 全局 Spring 容器可配置应用上下文引用,便于运行时动态管理 Bean 生命周期及重启动作 */ + private static ConfigurableApplicationContext context; + + /** + * 系统启动主入口(JAR / 本地开发模式) + * + * @param args 命令行启动参数(如 --server.port、--spring.profiles.active 等) + */ + public static void main(String[] args) { + context = SpringApplication.run(MainApplication.class, args); + } + + /** + * 配置 Servlet 上下文构建器(WAR 外部容器部署模式) + * + * @param builder Spring Boot 提供的应用构建器 + * @return 绑定当前引导类的构建器实例 + */ + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(new Class[]{MainApplication.class}); + } + + /** + * 【运维亮点】在进程运行期间动态热重启 Spring 应用上下文 + * + *

实现原理: + * 1. 获取原应用的启动参数列表(ApplicationArguments); + * 2. 在独立的非守护线程(Non-Daemon Thread)中先关闭现有应用上下文释放网络端口、数据库连接池等资源; + * 3. 重新以原始参数启动新的 Spring 上下文,避免重启整个 JVM 虚拟机进程,大幅缩短系统重载耗时。 + */ + public static void restart() { + ApplicationArguments args = (ApplicationArguments)context.getBean(ApplicationArguments.class); + Thread thread = new Thread(() -> { + context.close(); + context = SpringApplication.run(MainApplication.class, args.getSourceArgs()); + }); + thread.setDaemon(false); + thread.start(); + } +} diff --git a/src/main/java/com/midm/app/AppConfig.java b/src/main/java/com/midm/app/AppConfig.java new file mode 100644 index 0000000..8ab7a86 --- /dev/null +++ b/src/main/java/com/midm/app/AppConfig.java @@ -0,0 +1,29 @@ +package com.midm.app; + +import com.midm.model.system.SystemSetting; +import com.mitac.cell.constant.SizeConst; +import javax.servlet.MultipartConfigElement; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.servlet.MultipartConfigFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.util.unit.DataSize; + +@Configuration +public class AppConfig { + @Autowired + private MongoTemplate mongoTemplate; + + @Bean + public MultipartConfigElement multipartConfigElement() { + SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("files.maxUploadSize")), SystemSetting.class); + long maxUploadSize = setting == null ? SizeConst.SIZE_1G * 4L : setting.getAsLong(); + MultipartConfigFactory factory = new MultipartConfigFactory(); + factory.setMaxFileSize(DataSize.ofBytes(maxUploadSize)); + factory.setMaxRequestSize(DataSize.ofBytes(maxUploadSize)); + return factory.createMultipartConfig(); + } +} diff --git a/src/main/java/com/midm/app/AsyncConfig.java b/src/main/java/com/midm/app/AsyncConfig.java new file mode 100644 index 0000000..8ea96cc --- /dev/null +++ b/src/main/java/com/midm/app/AsyncConfig.java @@ -0,0 +1,57 @@ +package com.midm.app; + +import java.lang.reflect.Method; +import java.util.concurrent.Executor; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; + +@Configuration +@EnableAsync +public class AsyncConfig implements AsyncConfigurer { + private static final int TASK_CORE_POOL_SIZE = 10; + private static final int TASK_MAX_POOL_SIZE = 20; + private static final int TASK_QUEUE_CAPACITY = 100; + private AsyncUncaughtExceptionHandler asyncExceptionHandler = new AsyncUncaughtExceptionHandler() { + public void handleUncaughtException(Throwable ex, Method method, Object... params) { + } + }; + + @Bean + @Primary + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(10); + executor.setMaxPoolSize(20); + executor.setQueueCapacity(100); + executor.setBeanName("asyncExecutor"); + executor.initialize(); + return executor; + } + + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return this.asyncExceptionHandler; + } + + @Bean + @Primary + public ThreadPoolTaskScheduler getTaskScheduler() { + ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); + taskScheduler.setPoolSize(50); + return taskScheduler; + } + + @Bean + public ThreadPoolTaskExecutor getTaskExcutor() { + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setCorePoolSize(5); + taskExecutor.setMaxPoolSize(50); + taskExecutor.setQueueCapacity(150); + return taskExecutor; + } +} diff --git a/src/main/java/com/midm/app/BasicAuthInterceptor.java b/src/main/java/com/midm/app/BasicAuthInterceptor.java new file mode 100644 index 0000000..f09fce5 --- /dev/null +++ b/src/main/java/com/midm/app/BasicAuthInterceptor.java @@ -0,0 +1,48 @@ +package com.midm.app; + +import com.google.common.base.Strings; +import com.midm.service.device.DeviceKeyService; +import com.midm.service.system.SettingsService; +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.util.Pair; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +@Component +public class BasicAuthInterceptor implements HandlerInterceptor { + @Autowired + DeviceKeyService deviceKeyService; + @Autowired + SettingsService settingsService; + + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String serialNo = request.getHeader("serialNo"); + if (Strings.isNullOrEmpty(serialNo)) { + return true; + } else { + String encryptString = request.getHeader("encryptString"); + Pair pair = this.deviceKeyService.isValidRsa(serialNo, encryptString); + if (Boolean.TRUE == pair.getFirst()) { + return true; + } else { + String errorMessage = (String)pair.getSecond(); + this.responseError(response, 403, errorMessage); + return false; + } + } + } + + private void responseError(HttpServletResponse response, int code, String message) { + response.setStatus(code); + response.setContentType("application/json"); + + try { + response.getWriter().write(String.format("{ \"message\": \" %s \"}", message)); + } catch (IOException var5) { + } + + } +} diff --git a/src/main/java/com/midm/app/DbConfig.java b/src/main/java/com/midm/app/DbConfig.java new file mode 100644 index 0000000..584b729 --- /dev/null +++ b/src/main/java/com/midm/app/DbConfig.java @@ -0,0 +1,265 @@ +package com.midm.app; + +import com.google.common.base.Strings; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URIBuilder; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; + +/** + * ====================================================================================== + * MongoDB 工业级高可用连接池与数据库配置类 (DbConfig) + * ====================================================================================== + * + *

【架构设计与高并发亮点】 + * 1. 业务场景: + * - 管理海量设备档案、高频时序遥测数据(GPS经纬度、电池SOH、网络数据流量)及企业操作审计日志。 + * 2. 【生产级连接池参数调优】: + * - `maxPoolSize`: 1000(支持高并发终端长连接上报写入); + * - `connectTimeoutMS`: 5000ms(连接超时自适应); + * - `maxIdleTimeMS`: 30000ms(空闲连接及时回收,避免占用云数据库物理句柄); + * - `waitqueuetimeoutms`: 5000ms(防止线程池排队积压导致雪崩)。 + * 3. 【分布式高可用集群支持】: + * - 支持单机、集群多节点逗号分隔(Replica Set 副本集模式); + * - 支持 `mongodb+srv://` 协议(如 AWS DocumentDB / MongoDB Atlas 云原生集群); + * - 写入策略:强制设置 `w=majority`(多数派确认,确保主从切换时数据零丢失)与 `retryWrites=true`。 + * 4. 【数据库索引自愈能力 (Index Migration & Self-Healing)】: + * - 在 {@link #fixDb} 中,系统启动时会自动探测并主动清除低效的单字段老索引(如 `midmLog` 的单字段索引), + * 确保复合索引(Compound Index)能够最高效命中执行计划。 + * + * @author MiDM Core Platform Team + */ +@Configuration +@EnableMongoRepositories({"com.midm.repository"}) +public class DbConfig extends AbstractMongoClientConfiguration { + + @Value("${mongo.servers:}") + private String dbServers; + + @Value("${mongo.uri:}") + private String dbUri; + + @Value("${mongo.scheme:mongodb}") + private String dbScheme; + + @Value("${mongo.host:127.0.0.1}") + private String dbHost; + + @Value("${mongo.port:27017}") + private Integer dbPort; + + @Value("${mongo.dbname:db_midm}") + private String dbName; + + @Value("${mongo.username:}") + private String dbUser; + + @Value("${mongo.password:}") + private String dbPassword; + + @Value("${mongo.ssl:false}") + private boolean sslEnabled; + + @Value("${mongo.keep_alive:true}") + private boolean keepAlive; + + /** 最大并发连接池容量(默认 1000,保障海量终端瞬间重连时平稳接入) */ + @Value("${mongo.maxPoolSize:1000}") + private int maxPoolSize; + + @Value("${mongo.connectionsPerHost: 1000}") + private int connectionsPerHost; + + @Value("${mongo.connection_multiplier:200}") + private int connectionMultiplier; + + @Value("${mongo.connect_timeout:5000}") + private int connectTimeout; + + @Value("${mongo.wait_timeout:5000}") + private int waitTimeout; + + @Value("${mongo.socket_timeout:0}") + private int socketTimeout; + + @Value("${mongo.idle_timeout:30000}") + private int idleTimeout; + + @Value("${mongo.replica_set:rs0}") + private String dbReplicaSet; + + /** + * 【动态连接串构建算法】根据配置文件自适应拼装生产级 MongoDB URI + * + * @return 包含完备连接池与安全参数的 ConnectionString + */ + private ConnectionString getConnectiontString() { + // 1. 支持逗号分隔的多节点集群配置解析(如 "node1:27017,node2:27017,node3:27017") + if (this.dbHost.contains(",")) { + String[] hosts = this.dbHost.split(","); + StringBuilder sb = new StringBuilder(); + for(String host : hosts) { + if (sb.length() > 0) { + sb.append(","); + } + host = host.toLowerCase().trim(); + int indexPort = host.indexOf(":"); + if (indexPort > 0) { + sb.append(host); + } else { + sb.append(host).append(":").append(this.dbPort); + } + } + this.dbHost = sb.toString(); + this.dbPort = null; + } else { + this.dbReplicaSet = null; + } + + URIBuilder uriBuilder = null; + ConnectionString connectionString = null; + try { + if (Strings.isNullOrEmpty(this.dbUri)) { + uriBuilder = new URIBuilder(); + } else { + uriBuilder = new URIBuilder(this.dbUri); + connectionString = new ConnectionString(this.dbUri); + } + } catch (Exception var9) { + return null; + } + + // 2. 注入高可靠性与强一致性参数:w=majority(多数派成功)、retryWrites=true(网络故障重试写入) + uriBuilder.setParameter("uuidRepresentation", "javaLegacy") + .setParameter("retryWrites", String.valueOf(true)) + .setParameter("w", "majority"); + + if (connectionString == null) { + if (Strings.isNullOrEmpty(uriBuilder.getScheme())) { + uriBuilder.setScheme(this.dbScheme); + } + if (Strings.isNullOrEmpty(uriBuilder.getHost())) { + uriBuilder.setHost(this.dbHost); + } + if (uriBuilder.getPort() < 0) { + uriBuilder.setPort(this.dbPort); + } + if (Strings.isNullOrEmpty(uriBuilder.getUserInfo()) && !Strings.isNullOrEmpty(this.dbUser)) { + uriBuilder.setUserInfo(this.dbUser, this.dbPassword); + } + List paths = uriBuilder.getPathSegments(); + if (paths != null && paths.size() != 0) { + this.dbName = (String)paths.get(0); + } else { + uriBuilder.setPath(this.dbName); + } + } else { + this.dbName = connectionString.getDatabase(); + } + + // 3. 动态配置连接池水线(Pool Size、Timeout、SSL 等) + List queryParams = uriBuilder.getQueryParams(); + Set params = new HashSet(); + queryParams.forEach((param) -> params.add(param.getName())); + + if (!params.contains("maxPoolSize")) { + uriBuilder.setParameter("maxPoolSize", String.valueOf(this.maxPoolSize)); + } + if (!params.contains("connectTimeoutMS")) { + uriBuilder.setParameter("connectTimeoutMS", String.valueOf(this.connectTimeout)); + } + if (!params.contains("maxIdleTimeMS")) { + uriBuilder.setParameter("maxIdleTimeMS", String.valueOf(this.idleTimeout)); + } + if (!params.contains("waitqueuetimeoutms")) { + uriBuilder.setParameter("waitqueuetimeoutms", String.valueOf(this.waitTimeout)); + } + + boolean isSrv = uriBuilder.getScheme().endsWith("+srv"); + if (!isSrv && !params.contains("ssl")) { + uriBuilder.setParameter("ssl", String.valueOf(this.sslEnabled)); + } + + if (!Strings.isNullOrEmpty(this.dbReplicaSet) && !params.contains("replicaSet")) { + uriBuilder.setParameter("replicaSet", this.dbReplicaSet); + } + + try { + URI mongoUri = uriBuilder.build(); + return new ConnectionString(mongoUri.toString()); + } catch (URISyntaxException e) { + e.printStackTrace(); + return null; + } + } + + /** + * 初始化创建 MongoClient 实例并触发自愈索引检查 + */ + @Override + public MongoClient mongoClient() { + ConnectionString connectionString = this.getConnectiontString(); + MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build(); + MongoClient client = MongoClients.create(mongoClientSettings); + // 执行启动期索引自愈与冲突清理 + this.fixDb(client); + return client; + } + + @Override + protected String getDatabaseName() { + return this.dbName; + } + + /** + * 开启实体类注解索引自动创建(@Indexed / @CompoundIndexes) + */ + @Override + protected boolean autoIndexCreation() { + return true; + } + + /** + * 【数据库索引自愈能力】 + *

扫描数据库集合,主动剔除历史版本中遗留的低效单字段索引, + * 避免其与当前版本的复合联合索引产生性能冲突。 + */ + private void fixDb(MongoClient client) { + MongoDatabase db = client.getDatabase(this.getDatabaseName()); + if (db != null) { + MongoCollection siteCollection = db.getCollection("site"); + if (siteCollection != null) { + siteCollection.listIndexes().forEach((index) -> { + String name = index.getString("name"); + if (name.equals("idName_1")) { + siteCollection.dropIndex(name); + } + }); + } + + MongoCollection logCollection = db.getCollection("midmLog"); + if (logCollection != null) { + logCollection.listIndexes().forEach((index) -> { + String name = index.getString("name"); + if (name.equals("category") || name.equals("forWhat")) { + logCollection.dropIndex(name); + } + }); + } + } + } +} diff --git a/src/main/java/com/midm/app/DbInitialize.java b/src/main/java/com/midm/app/DbInitialize.java new file mode 100644 index 0000000..90f470c --- /dev/null +++ b/src/main/java/com/midm/app/DbInitialize.java @@ -0,0 +1,454 @@ +package com.midm.app; + +import com.google.common.reflect.TypeToken; +import com.midm.model.device.DataUsage; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceLicense; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.DeviceProfileState; +import com.midm.model.device.DeviceReport; +import com.midm.model.device.ProfileApps; +import com.midm.model.device.ProfileScope; +import com.midm.model.file.AppFile; +import com.midm.model.log.MidmLog; +import com.midm.model.org.Site; +import com.midm.model.org.SiteFile; +import com.midm.model.org.SiteLicense; +import com.midm.model.org.User; +import com.midm.model.system.HostLicense; +import com.midm.model.system.LicenseModel; +import com.midm.model.system.SystemSetting; +import com.midm.service.system.RestoreService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mongodb.MongoNamespace; +import com.mongodb.client.ListIndexesIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.commons.compress.utils.Sets; +import org.bson.Document; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.index.CompoundIndexDefinition; +import org.springframework.data.mongodb.core.index.Index; +import org.springframework.data.mongodb.core.query.BasicQuery; +import org.springframework.data.mongodb.core.query.Collation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.data.mongodb.core.schema.JsonSchemaObject; +import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type; +import org.springframework.stereotype.Component; + +@Component +public class DbInitialize { + private static final long DB_SCHEME_VER_2 = 20092901L; + private static final long DB_SCHEME_VER_3 = 22111002L; + private static final long DB_SCHEME_VER_4 = 23072101L; + private static final long DB_SCHEME_VER_5 = 23082501L; + private static final long DB_SCHEME_VER_6 = 24022701L; + private String KEY_DB_SCHEME = "db.scheme"; + @Autowired + private MongoTemplate mongoTemplate; + @Autowired + private RestoreService restoreService; + + @EventListener({ContextRefreshedEvent.class}) + public void contextRefreshedEvent() { + this.initializeDb(); + this.updateScheme(); + } + + private void initializeDb() { + MongoCollection resourceMessageCollection = this.mongoTemplate.getCollection("resourceMessage"); + if (resourceMessageCollection == null || resourceMessageCollection.countDocuments() == 0L) { + this.restoreService.restore((String)null); + } + + if (this.mongoTemplate.collectionExists(SystemSetting.class)) { + SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("db.indexed")), SystemSetting.class); + if (setting == null) { + Set collections = this.mongoTemplate.getCollectionNames(); + collections.forEach((collection) -> this.mongoTemplate.getCollection(collection).dropIndexes()); + this.mongoTemplate.save(new SystemSetting("db.indexed", String.valueOf(true))); + } + } + + if (this.mongoTemplate.collectionExists(Site.class)) { + Query query = Query.query(Criteria.where("settings.noti.sendEmail").exists(false)); + Update update = (new Update()).set("settings.noti.sendEmail", true); + this.mongoTemplate.updateMulti(query, update, Site.class); + String[] forWhats = new String[]{"general", "urgent", "maintenance"}; + Document value = (new Document("enabled", true)).append("roles", new Document("SUPERVISOR", true)); + + for(String forWhat : forWhats) { + String key = "settings.noti.support." + forWhat; + query = Query.query(Criteria.where(key).exists(false)); + update = (new Update()).set(key, value); + this.mongoTemplate.updateMulti(query, update, Site.class); + } + } + + if (this.mongoTemplate.collectionExists(Device.class) && this.mongoTemplate.count(new Query(), Device.class) > 0L) { + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.group(new String[]{"$profile.hardware_info.serial_no"}).addToSet("id").as("uuids").max("updated").as("latest").count().as("count"), Aggregation.match(Criteria.where("count").gt(1))}); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, Device.class, Document.class); + results.forEach((result) -> { + String serialNo = result.getString("_id"); + Date updated = (Date)result.get("latest"); + this.mongoTemplate.remove(Query.query(Criteria.where("profile.hardware_info.serial_no").is(serialNo).and("updated").ne(updated)), Device.class); + }); + } + + if (this.mongoTemplate.collectionExists("appFile")) { + BasicQuery basicQuery = new BasicQuery(new Document("$expr", new Document("$eq", Arrays.asList("$name", "$fileInfo.fileName")))); + List apps = this.mongoTemplate.find(basicQuery, AppFile.class); + apps.forEach((app) -> this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(app.getFileUuid())), Update.update("name", app.getLabel()), AppFile.class)); + basicQuery = new BasicQuery(new Document("appInfo.targetSdkVersion", new Document("$type", "string"))); + apps = this.mongoTemplate.find(basicQuery, AppFile.class); + apps.forEach((app) -> { + int version = app.getTargetSdkVersion(); + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(app.getFileUuid())), Update.update("appInfo.targetSdkVersion", version), AppFile.class); + }); + } + + if (this.mongoTemplate.collectionExists(DeviceReport.class)) { + this.dropIndex(DeviceReport.class, "deviceUuid"); + } + + this.ensureIndex(Site.class, true, "idName"); + this.ensureIndex(Site.class, false, "profile.name"); + this.ensureDeviceSerialIndex(); + this.ensureIndex(Device.class, false, "owner.uuid", "deviceGroup.uuid"); + this.ensureIndex(DeviceProfile.class, false, "deviceProfileGroup.uuid"); + this.ensureIndex(DeviceProfileState.class, false, "_id.deviceUuid"); + this.ensureIndex(DeviceProfileState.class, false, "_id.profileUuid"); + this.ensureIndex(DataUsage.class, false, "deviceUuid"); + this.ensureIndex(DataUsage.class, false, "from"); + this.ensureIndex(DataUsage.class, false, "to"); + this.ensureIndex(DeviceReport.class, false, "properties.deviceProfile.uuid", "properties.deviceProfile.updated"); + this.ensureIndex(DeviceReport.class, false, "reportedAt"); + this.ensureIndex(MidmLog.class, false, "category", "loggedAt"); + } + + private void ensureIndex(Class entityClass, boolean unique, String... keys) { + try { + if (keys.length > 0) { + Document indexDefinition = new Document(); + + for(String key : keys) { + indexDefinition.append(key, 1); + } + + CompoundIndexDefinition index = new CompoundIndexDefinition(indexDefinition); + if (unique) { + index.unique(); + } + + this.mongoTemplate.indexOps(entityClass).ensureIndex(index); + } + } catch (Exception var9) { + } + + } + + private void dropIndex(Class entityClass, String... keys) { + if (this.mongoTemplate.collectionExists(entityClass)) { + MongoCollection collection = this.getCollection(entityClass); + ListIndexesIterable indexes = collection.listIndexes(); + Set keySet = Sets.newHashSet(keys); + MongoCursor var6 = indexes.iterator(); + + while(var6.hasNext()) { + Document index = (Document)var6.next(); + Document keyMap = (Document)index.get("key", Document.class); + if (keyMap.keySet().equals(keySet)) { + collection.dropIndex(index.getString("name")); + break; + } + } + + } + } + + private void ensureDeviceSerialIndex() { + MongoCollection collection = this.getCollection(Device.class); + ListIndexesIterable indexes = collection.listIndexes(); + boolean isConfigured = false; + MongoCursor indexDefinition = indexes.iterator(); + + while(indexDefinition.hasNext()) { + Document index = (Document)indexDefinition.next(); + Document keys = (Document)index.get("key", Document.class); + if (keys.containsKey("profile.hardware_info.serial_no") && keys.containsKey("siteUuid")) { + if (!index.containsKey("collation")) { + collection.dropIndex(index.getString("name")); + } else { + isConfigured = true; + } + } else if (keys.size() == 1 && keys.containsKey("siteUuid")) { + collection.dropIndex(index.getString("name")); + } + } + + if (!isConfigured) { + Document indexDefinition = (new Document("siteUuid", 1)).append("profile.hardware_info.serial_no", 1); + Index index = (new CompoundIndexDefinition(indexDefinition)).collation(Collation.of("en").strength(2)); + this.mongoTemplate.indexOps(Device.class).ensureIndex(index); + } + + collection = this.getCollection(DeviceLicense.class); + indexes = collection.listIndexes(); + indexDefinition = indexes.iterator(); + + while(indexDefinition.hasNext()) { + Document index = (Document)indexDefinition.next(); + Document keys = (Document)index.get("key", Document.class); + if (keys.size() == 1 && keys.containsKey("plan")) { + collection.dropIndex(index.getString("name")); + } + } + + } + + private void updateScheme() { + if (this.mongoTemplate.collectionExists("siteReport")) { + MongoCollection collection = this.mongoTemplate.getCollection("siteReport"); + if (this.mongoTemplate.collectionExists(SiteFile.class)) { + collection.drop(); + } else { + MongoNamespace nameSpace = collection.getNamespace(); + collection.renameCollection(new MongoNamespace(nameSpace.getDatabaseName(), "siteFile")); + } + } + + boolean isStandalone = this.isStandalone(); + if (this.getDbScheme() < 20092901L) { + Query query = Query.query(Criteria.where("profile.tel").exists(true)); + Update update = new Update(); + update.rename("profile.tel", "profile.phone"); + this.mongoTemplate.updateMulti(query, update, User.class); + this.mongoTemplate.updateMulti(query, update, Site.class); + this.mongoTemplate.updateMulti(new Query(Criteria.where("isLite").exists(true)), (new Update()).unset("isLite"), "site"); + this.mongoTemplate.updateMulti(new Query(Criteria.where("isMust").exists(true)), (new Update()).unset("isMust"), "site"); + this.mongoTemplate.updateMulti(new Query(Criteria.where("isReseller").exists(true)), (new Update()).unset("isReseller"), "site"); + if (isStandalone) { + this.mongoTemplate.updateMulti(new Query(), Update.update("profile.model", "midm"), Site.class); + } + + query = Query.query(Criteria.where("profile.owner.tel").exists(true)); + update = new Update(); + update.rename("profile.owner.tel", "profile.owner.phone"); + this.mongoTemplate.updateMulti(query, update, Device.class); + } + + if (this.getDbScheme() < 22111002L) { + if (this.mongoTemplate.collectionExists("user")) { + Query query = Query.query(Criteria.where("settings.report").exists(true)); + Update update = (new Update()).unset("settings.report"); + this.mongoTemplate.updateMulti(query, update, User.class); + } + + Query query = Query.query((new Criteria()).orOperator(new Criteria[]{Criteria.where("scope.group").type(new JsonSchemaObject.Type[]{Type.STRING}), Criteria.where("apps.install.uuid").type(new JsonSchemaObject.Type[]{Type.STRING}), Criteria.where("apps.install.0").type(new JsonSchemaObject.Type[]{Type.STRING})})); + query.fields().include(new String[]{"scope.group", "apps.install"}); + List profiles = this.mongoTemplate.find(query, Document.class, "deviceProfile"); + if (profiles != null && !profiles.isEmpty()) { + java.lang.reflect.Type installAppType = (new TypeToken() { + }).getType(); + profiles.forEach((profile) -> { + Update update = new Update(); + Object _id = profile.get("_id"); + Document scopeObj = (Document)profile.get("scope"); + if (scopeObj != null) { + List groups = scopeObj.getList("group", Object.class); + if (groups != null && !groups.isEmpty() && groups.get(0) instanceof String) { + ProfileScope scope = (ProfileScope)McJsonUtils.toObject(scopeObj.toJson(), ProfileScope.class); + Set groupUuids = scope.getGroup(); + List existingGroups = this.mongoTemplate.find(Query.query(Criteria.where("_id").in(groupUuids)), DeviceGroup.class); + Set existingUuids = (Set)existingGroups.stream().map((groupItem) -> groupItem.getUuid()).collect(Collectors.toSet()); + scope.setGroup(existingUuids); + update.set("scope", scope); + } + } + + Document apps = (Document)profile.get("apps"); + if (apps != null) { + List install = apps.getList("install", Object.class); + if (install != null && !install.isEmpty()) { + List installApps = new ArrayList(); + if (install.get(0) instanceof String) { + for(Object uuid : install) { + UUID appUuid = UUID.fromString((String)uuid); + AppFile appFile = (AppFile)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(appUuid)), AppFile.class); + if (appFile != null) { + ProfileApps.InstallApp app = new ProfileApps.InstallApp(appFile); + installApps.add(app); + } + } + } else { + installApps = (List)McJsonUtils.toObject(McJsonUtils.toJson(install), installAppType); + Iterator it = installApps.iterator(); + + while(it.hasNext()) { + ProfileApps.InstallApp app = (ProfileApps.InstallApp)it.next(); + if (!this.mongoTemplate.exists(Query.query(Criteria.where("_id").is(app.getUuid())), AppFile.class)) { + it.remove(); + } + } + } + + if (installApps.isEmpty()) { + update.unset("apps.install"); + } else { + update.set("apps.install", installApps); + } + } + } + + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(_id)), update, DeviceProfile.class); + }); + } + + query = Query.query(Criteria.where("profile.startsOn").type(new JsonSchemaObject.Type[]{Type.dateType()})); + List deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class); + if (!deviceProfiles.isEmpty()) { + deviceProfiles.forEach((profile) -> { + DbObject profileObj = profile.getProfile(); + Date startsDate = (Date)profileObj.get("startsOn"); + String starts = McDateTimeUtils.toString(new DateTime(startsDate), "yyyy-MM-dd"); + Update update = Update.update("profile.startsOn", starts); + Object endsDate = profileObj.get("ends"); + if (endsDate != null) { + if (endsDate instanceof Date) { + String ends = McDateTimeUtils.toString(new DateTime(endsDate), "yyyy-MM-dd"); + update.set("profile.ends", ends); + } else if (endsDate instanceof String) { + String ends = ((String)endsDate).substring(0, 10); + update.set("profile.ends", ends); + } + } + + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class); + }); + } + + query = Query.query(Criteria.where("profile.startsOn").regex(".{11,}")); + deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class); + if (!deviceProfiles.isEmpty()) { + deviceProfiles.forEach((profile) -> { + DbObject profileObj = profile.getProfile(); + String startsDate = profileObj.getString("startsOn"); + Update update = Update.update("profile.startsOn", startsDate.substring(0, 10)); + Object endsDate = profileObj.get("ends"); + if (endsDate != null) { + if (endsDate instanceof Date) { + String ends = McDateTimeUtils.toString(new DateTime(endsDate), "yyyy-MM-dd"); + update.set("profile.ends", ends); + } else if (endsDate instanceof String) { + String ends = ((String)endsDate).substring(0, 10); + update.set("profile.ends", ends); + } + } + + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class); + }); + } + + String[] settingFields = new String[]{"systemProperties", "globalSettings", "systemSettings", "secureSettings"}; + query = new Query(); + List settingsCriteria = new ArrayList(); + + for(String field : settingFields) { + settingsCriteria.add(Criteria.where("settings." + field).type(new JsonSchemaObject.Type[]{Type.ARRAY})); + query.fields().include("settings." + field); + } + + query.addCriteria((new Criteria()).orOperator(settingsCriteria)); + profiles = this.mongoTemplate.find(query, Document.class, "deviceProfile"); + Update update = new Update(); + if (profiles != null && !profiles.isEmpty()) { + profiles.forEach((profile) -> { + Object _id = profile.get("_id"); + Document settings = (Document)profile.get("settings"); + if (settings != null) { + for(String field : settingFields) { + List categorySettings = settings.getList(field, Document.class); + if (categorySettings != null && !categorySettings.isEmpty()) { + try { + Map newValue = (Map)categorySettings.stream().collect(Collectors.toMap((e) -> e.get("key"), (e) -> e.get("value"))); + update.set("settings." + field, newValue); + } catch (Exception var12) { + update.unset("settings." + field); + } + } + } + } + + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(_id)), update, DeviceProfile.class); + }); + } + } + + if (this.getDbScheme() < 23072101L) { + if (isStandalone) { + this.mongoTemplate.dropCollection(LicenseModel.class); + this.mongoTemplate.dropCollection(DeviceLicense.class); + this.mongoTemplate.dropCollection(SiteLicense.class); + this.mongoTemplate.updateMulti(new Query(), (new Update()).unset("license").unset("licensed").unset("licenseExpiry"), Device.class); + } + + this.mongoTemplate.updateMulti(new Query(), (new Update()).unset("priority"), DeviceProfile.class); + Query query = Query.query(Criteria.where("profile.weekOptions").exists(true)); + List profiles = this.mongoTemplate.find(query, DeviceProfile.class); + profiles.forEach((profile) -> { + List options = (List)profile.getProfile("weekOptions"); + List newOptions = (List)options.stream().map((week) -> week.intValue() + 1).collect(Collectors.toList()); + Update update = Update.update("updated", new Date(profile.getUpdated().getTime() + 1L)).set("profile.weekOptions", newOptions); + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class); + }); + } + + if (this.getDbScheme() < 23082501L) { + this.mongoTemplate.updateMulti(Query.query(Criteria.where("state").exists(false)), Update.update("state", "done"), DeviceProfileState.class); + this.mongoTemplate.save(new SystemSetting(this.KEY_DB_SCHEME, 23082501L)); + } + + if (this.getDbScheme() < 24022701L) { + Update update = new Update(); + update.unset("settings.page"); + this.mongoTemplate.updateMulti(new Query(), update, User.class); + this.mongoTemplate.save(new SystemSetting(this.KEY_DB_SCHEME, 24022701L)); + } + + } + + private MongoCollection getCollection(Class entityClass) { + return this.mongoTemplate.getCollection(this.mongoTemplate.getCollectionName(entityClass)); + } + + private long getDbScheme() { + SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(this.KEY_DB_SCHEME)), SystemSetting.class); + return setting != null ? setting.getAsLong() : -1L; + } + + private boolean isStandalone() { + HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class); + return license != null && license.isStandalone(); + } +} diff --git a/src/main/java/com/midm/app/GlobalController.java b/src/main/java/com/midm/app/GlobalController.java new file mode 100644 index 0000000..b5ab458 --- /dev/null +++ b/src/main/java/com/midm/app/GlobalController.java @@ -0,0 +1,127 @@ +package com.midm.app; + +import com.midm.model.org.User; +import com.midm.security.UserPrincipal; +import com.midm.service.org.SiteService; +import com.midm.service.system.HelpMessageService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.LocaleService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.utils.McStringUtils; +import java.util.Date; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.info.BuildProperties; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestParam; + +@ControllerAdvice +public final class GlobalController { + private static final String[] excludeBindingPrefixes = new String[]{"/api/", "/img/", "/profile/", "/client/", "/icon/", "/store/", "/logo/", "/device/", "/file/", "/must/", "/userfile/", "/barcode/", "/dpc/"}; + @Autowired + private BuildProperties buildProperties; + @Autowired + protected LocaleService localeService; + @Autowired + private SettingsService settingsService; + @Autowired + private HostLicenseService licenseService; + @Autowired + protected SiteService siteService; + @Autowired + private HelpMessageService helpMessageService; + @Value("#{servletContext.contextPath}") + private String servletContextPath; + + @ModelAttribute("buildVersion") + public String buildVersion() { + return this.buildProperties.getVersion(); + } + + @ModelAttribute("buildTime") + public String buildTime() { + return Date.from(this.buildProperties.getTime()).toString(); + } + + @ModelAttribute("user") + public Object user(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) String language) { + if (this.bindModel(request)) { + User user = authentication == null ? this.guest(request, language) : UserPrincipal.getUser(authentication); + if (user.getSite() == null && user.getSiteUuid() != null) { + user.setSite(this.siteService.findByUuid(user.getSiteUuid())); + } + + return user; + } else { + return null; + } + } + + @ModelAttribute("settings") + public SettingsService settings() { + return this.settingsService; + } + + @ModelAttribute("locales") + public LocaleService locales() { + return this.localeService; + } + + @ModelAttribute("helpService") + public HelpMessageService helpService() { + return this.helpMessageService; + } + + @ModelAttribute("isHostValid") + public boolean isHostValid() { + return this.licenseService.isValid(); + } + + @ModelAttribute("deviceLimit") + public int deviceLimit() { + return this.licenseService.getDeviceLimit(); + } + + @ModelAttribute("siteService") + public SiteService siteService() { + return this.siteService; + } + + @ModelAttribute("contextPath") + public String contextPath() { + return this.servletContextPath + "/"; + } + + private User guest(HttpServletRequest request, String localeTag) { + User user = new User(); + user.setName("Guest"); + if (!McStringUtils.isValid(localeTag)) { + localeTag = request.getLocale().toLanguageTag(); + } + + request.getSession().setAttribute("language", localeTag); + Locale curLocale = Locale.forLanguageTag(localeTag); + if (curLocale == null) { + curLocale = request.getLocale(); + } + + user.setLocale(this.localeService.findAltLocale(curLocale)); + return user; + } + + public boolean bindModel(HttpServletRequest request) { + String uri = request.getRequestURI(); + + for(String prefix : excludeBindingPrefixes) { + if (uri.startsWith(this.servletContextPath + prefix)) { + return false; + } + } + + return true; + } +} diff --git a/src/main/java/com/midm/app/InterceptorConfig.java b/src/main/java/com/midm/app/InterceptorConfig.java new file mode 100644 index 0000000..6ae4a3a --- /dev/null +++ b/src/main/java/com/midm/app/InterceptorConfig.java @@ -0,0 +1,16 @@ +package com.midm.app; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class InterceptorConfig implements WebMvcConfigurer { + @Autowired + private BasicAuthInterceptor basicAuthInterceptor; + + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(this.basicAuthInterceptor).addPathPatterns(new String[]{"/api/**"}); + } +} diff --git a/src/main/java/com/midm/app/LocaleConfig.java b/src/main/java/com/midm/app/LocaleConfig.java new file mode 100644 index 0000000..c5c0921 --- /dev/null +++ b/src/main/java/com/midm/app/LocaleConfig.java @@ -0,0 +1,46 @@ +package com.midm.app; + +import com.midm.service.system.LocaleService; +import java.text.MessageFormat; +import java.util.Locale; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.AbstractMessageSource; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.i18n.SessionLocaleResolver; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.templateresolver.StringTemplateResolver; + +@Configuration +public class LocaleConfig { + @Bean({"stringTemplateEngine"}) + public TemplateEngine stringTemplateEngine() { + TemplateEngine templateEngine = new TemplateEngine(); + templateEngine.setTemplateResolver(new StringTemplateResolver()); + return templateEngine; + } + + @Bean + public LocaleResolver localeResolver() { + SessionLocaleResolver localeResolver = new SessionLocaleResolver(); + localeResolver.setDefaultLocale(Locale.US); + return localeResolver; + } + + @Bean + public MessageSource messageSource() { + return new ResourceMessageSource(); + } + + private class ResourceMessageSource extends AbstractMessageSource { + @Autowired + private LocaleService localeService; + + protected MessageFormat resolveCode(String code, Locale locale) { + String msg = this.localeService.getMessage(locale, code); + return this.createMessageFormat(msg, locale); + } + } +} diff --git a/src/main/java/com/midm/app/PropertiesConfig.java b/src/main/java/com/midm/app/PropertiesConfig.java new file mode 100644 index 0000000..4a26bed --- /dev/null +++ b/src/main/java/com/midm/app/PropertiesConfig.java @@ -0,0 +1,51 @@ +package com.midm.app; + +import com.mitac.cell.system.OsInfo; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; + +@Configuration +public class PropertiesConfig { + @Bean + public static PropertySourcesPlaceholderConfigurer properties() { + PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); + List resourceLst = new ArrayList(); + File file = new File(getConfigFolder(), "midm.properties"); + if (!file.exists()) { + initProperties(file); + } + + resourceLst.add(new FileSystemResource(file)); + ppc.setLocations((Resource[])resourceLst.toArray(new Resource[0])); + return ppc; + } + + private static void initProperties(File file) { + Properties properties = new Properties(); + properties.setProperty("mongo.uri", "mongodb://username:password@127.0.0.1:27017/dbname"); + + try { + OutputStream os = new FileOutputStream(file); + properties.store(os, "MiDM Properties"); + os.close(); + } catch (FileNotFoundException var3) { + } catch (IOException var4) { + } + + } + + private static File getConfigFolder() { + return (new OsInfo()).getConfigFolder("MiDM"); + } +} diff --git a/src/main/java/com/midm/app/SecurityConfig.java b/src/main/java/com/midm/app/SecurityConfig.java new file mode 100644 index 0000000..2ea75e1 --- /dev/null +++ b/src/main/java/com/midm/app/SecurityConfig.java @@ -0,0 +1,129 @@ +package com.midm.app; + +import com.google.api.client.util.Value; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.SessionCookieConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.info.BuildProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.boot.web.servlet.ServletContextInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.firewall.HttpFirewall; +import org.springframework.security.web.firewall.StrictHttpFirewall; +import org.springframework.security.web.header.writers.StaticHeadersWriter; +import org.springframework.security.web.util.matcher.AnyRequestMatcher; +import org.springframework.web.filter.ForwardedHeaderFilter; + +/** + * ====================================================================================== + * 企业安全与 HTTP 防火墙配置类 (SecurityConfig) + * ====================================================================================== + * + *

【架构设计与安全防护亮点】 + * 1. 采用 Spring Security 5.7+ 现代组件化安全过滤链配置({@link SecurityFilterChain})。 + * 2. 【会话 Cookie 安全加固】: + * - 强制开启 `HttpOnly`(防御 XSS 跨站脚本窃取 Cookie)与 `Secure`(仅限 HTTPS 加密传输)。 + * 3. 【网络防火墙与反向代理适配 (Reverse Proxy Header)】: + * - 配置 {@link ForwardedHeaderFilter} 放在过滤器链最前端(`Integer.MIN_VALUE`), + * 精准获取经过 Nginx / ALB 代理后终端的真实客户端 IP(X-Forwarded-For); + * - 自定义 {@link StrictHttpFirewall}:放行 URL 编码斜杠(`%2F`)与百分号, + * 支持 Base64 加密的动态 Token 路由安全通过。 + * 4. 【传输安全 (HSTS) 与内容安全策略 (CSP)】: + * - 启用 HSTS (HTTP Strict Transport Security) 预加载,强制客户端全站使用 HTTPS; + * - 密码加密方案:采用工业级单向散列加盐算法 {@link BCryptPasswordEncoder}。 + * + * @author MiDM Core Platform Team + */ +@Configuration +public class SecurityConfig { + + @Autowired + private BuildProperties buildProperties; + + @Value("${spring.thymeleaf.cache: true}") + private boolean isDebug; + + /** + * 配置 Servlet 上下文 Cookie 安全属性 + */ + @Bean + public ServletContextInitializer servletContextInitializer() { + return new ServletContextInitializer() { + public void onStartup(ServletContext servletContext) throws ServletException { + SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig(); + sessionCookieConfig.setHttpOnly(SecurityConfig.this.isDebug); + sessionCookieConfig.setSecure(SecurityConfig.this.isDebug); + } + }; + } + + /** + * 【核心安全过滤链】配置认证、防护头与 CSP 策略 + */ + @Bean + public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { + // 写入统一的服务端指纹安全响应头 + StaticHeadersWriter headerWriter = new StaticHeadersWriter("Server", new String[]{"MiDM Host/MiTAC Digital", this.buildProperties.getVersion()}); + + // 针对 API 与 WebSocket 交互关闭 CSRF,禁用默认表单与 Basic 认证(由系统自定义 Token 过滤器接管) + httpSecurity.csrf((csrf) -> csrf.disable()) + .httpBasic((httpBasic) -> httpBasic.disable()) + .formLogin((formLogin) -> formLogin.disable()); + + // 配置内容安全策略 (CSP) + httpSecurity.headers((headers) -> headers.addHeaderWriter(headerWriter) + .contentSecurityPolicy("default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *;")); + + // 强制启用 HSTS 传输安全保障 + httpSecurity.headers((headers) -> headers.httpStrictTransportSecurity().preload(true).requestMatcher(AnyRequestMatcher.INSTANCE)); + + return (SecurityFilterChain)httpSecurity.build(); + } + + /** + * 反向代理转发头过滤器(保障真实 IP 提取) + */ + @Bean + public FilterRegistrationBean forwardedHeaderFilter() { + FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); + filterRegistrationBean.setFilter(new ForwardedHeaderFilter()); + filterRegistrationBean.setOrder(Integer.MIN_VALUE); + return filterRegistrationBean; + } + + /** + * 自定义 HTTP 防火墙规约 + */ + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> web.httpFirewall(this.httpFirewall()); + } + + /** + * 放宽特殊字符以兼容 Base64 令牌与 RESTful 动态参数 + */ + @Bean + public HttpFirewall httpFirewall() { + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowSemicolon(true); + firewall.setAllowUrlEncodedPeriod(true); + firewall.setAllowUrlEncodedPercent(true); + firewall.setAllowUrlEncodedSlash(true); + return firewall; + } + + /** + * 全局密码散列加密器(BCrypt) + */ + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/src/main/java/com/midm/app/StartupKeeper.java b/src/main/java/com/midm/app/StartupKeeper.java new file mode 100644 index 0000000..e236cb5 --- /dev/null +++ b/src/main/java/com/midm/app/StartupKeeper.java @@ -0,0 +1,71 @@ +package com.midm.app; + +import com.midm.service.device.DeviceService; +import com.midm.service.file.ReportService; +import com.midm.service.news.NewsMessageService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HelpMessageService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.LocaleService; +import com.midm.service.system.RestoreService; +import com.midm.service.system.SettingsService; +import java.util.TimeZone; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class StartupKeeper { + @Autowired + private HostLicenseService hostLicenseService; + @Autowired + private DeviceService deviceService; + @Autowired + private SettingsService settingsService; + @Autowired + private LocaleService localeService; + @Autowired + private UserService userService; + @Autowired + private HelpMessageService helpMessageService; + @Autowired + private NewsMessageService newsMessageService; + @Autowired + private ReportService reportService; + @Autowired + private SiteService siteService; + @Autowired + private RestoreService restoreService; + + @EventListener({ContextRefreshedEvent.class}) + private void contextRefreshedEvent() { + this.setDefaultTimeZone(); + this.settingsService.loadSettings(); + if (this.settingsService.syncOnStarts()) { + this.restoreService.restore((String)null); + } + + this.hostLicenseService.validateLicense(); + this.localeService.loadLocaleAndResources(); + this.helpMessageService.loadMessages(); + if (this.hostLicenseService.isPrimaryServer()) { + this.userService.updateUserNameIfNotExists(); + this.userService.clearExpiredTokens(); + this.reportService.expireReport(); + this.deviceService.initDeviceStatus(); + this.deviceService.clearOrphans(); + this.siteService.clearOrphans(); + this.newsMessageService.removeExpiredMessages(); + this.newsMessageService.scheduleToNotify(); + } + + } + + private void setDefaultTimeZone() { + TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC"); + System.setProperty("user.timezone", defaultTimeZone.getID()); + TimeZone.setDefault(defaultTimeZone); + } +} diff --git a/src/main/java/com/midm/app/WebSocketConfig.java b/src/main/java/com/midm/app/WebSocketConfig.java new file mode 100644 index 0000000..868bcfe --- /dev/null +++ b/src/main/java/com/midm/app/WebSocketConfig.java @@ -0,0 +1,40 @@ +package com.midm.app; + +import com.midm.websocket.message.QueryHandler; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.config.annotation.EnableWebSocket; +import org.springframework.web.socket.config.annotation.WebSocketConfigurer; +import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; + +/** + * ====================================================================================== + * WebSocket 全双工通信配置类 + * ====================================================================================== + * + *

【架构设计与业务场景】 + * 1. 负责开启系统全双工实时通信能力({@link EnableWebSocket}),作为物联网终端与云端管理控制台的接入网关。 + * 2. 路由映射:将 "/query" 端点绑定到核心消息处理器 {@link QueryHandler}。 + * 3. 跨域策略:允许跨域请求(AllowedOrigins: "*"),支持 Web 前端管理后台和不同子网终端的安全接入。 + * + * @author MiDM Core Platform Team + */ +@Configuration +@EnableWebSocket +public class WebSocketConfig implements WebSocketConfigurer { + + /** 核心 WebSocket 消息与连接生命周期处理器 */ + @Autowired + private QueryHandler queryHandler; + + /** + * 注册 WebSocket 处理器与通信端点 + * + * @param registry WebSocket 处理器注册中心 + */ + @Override + public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { + // 注册 "/query" 端点,用于处理终端注册(ENROLL)、遥测上报(REPORT)、心跳(PING/PONG)及实时控制指令下发 + registry.addHandler(this.queryHandler, new String[]{"/query"}).setAllowedOrigins(new String[]{"*"}); + } +} diff --git a/src/main/java/com/midm/app/converter/DateConverter.java b/src/main/java/com/midm/app/converter/DateConverter.java new file mode 100644 index 0000000..c0a63b3 --- /dev/null +++ b/src/main/java/com/midm/app/converter/DateConverter.java @@ -0,0 +1,33 @@ +package com.midm.app.converter; + +import com.mitac.cell.utils.McDateTimeUtils; +import java.util.Date; +import org.joda.time.DateTime; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +public class DateConverter implements Converter { + public Date convert(String source) { + DateTime date = null; + + try { + date = new DateTime(new Date(Long.parseLong(source))); + } catch (Exception var6) { + try { + date = DateTime.parse(source); + } catch (Exception var5) { + date = McDateTimeUtils.parseDate(source, (String)null); + if (date == null) { + date = McDateTimeUtils.parseDate(source, "E, d MMM yyyy HH:mm:ss Z 'GMT'"); + } + + if (date == null) { + date = McDateTimeUtils.parseDate(source, "E, d MMM yyyy HH:mm:ss Z z"); + } + } + } + + return date == null ? null : date.toDate(); + } +} diff --git a/src/main/java/com/midm/app/converter/DirectionConverter.java b/src/main/java/com/midm/app/converter/DirectionConverter.java new file mode 100644 index 0000000..3caec26 --- /dev/null +++ b/src/main/java/com/midm/app/converter/DirectionConverter.java @@ -0,0 +1,13 @@ +package com.midm.app.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.stereotype.Component; + +@Component +public class DirectionConverter implements Converter { + public Sort.Direction convert(String source) { + return Direction.valueOf(source.toUpperCase()); + } +} diff --git a/src/main/java/com/midm/app/converter/JsonElementConverter.java b/src/main/java/com/midm/app/converter/JsonElementConverter.java new file mode 100644 index 0000000..0c6b836 --- /dev/null +++ b/src/main/java/com/midm/app/converter/JsonElementConverter.java @@ -0,0 +1,20 @@ +package com.midm.app.converter; + +import com.google.gson.JsonElement; +import com.mitac.cell.utils.McJsonUtils; +import java.net.URLDecoder; +import java.nio.charset.Charset; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +public class JsonElementConverter implements Converter { + public JsonElement convert(String source) { + try { + source = URLDecoder.decode(source, Charset.defaultCharset()); + return McJsonUtils.toJsonElement(source); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/midm/app/converter/JsonObjectConverter.java b/src/main/java/com/midm/app/converter/JsonObjectConverter.java new file mode 100644 index 0000000..c314452 --- /dev/null +++ b/src/main/java/com/midm/app/converter/JsonObjectConverter.java @@ -0,0 +1,20 @@ +package com.midm.app.converter; + +import com.google.gson.JsonObject; +import com.mitac.cell.utils.McJsonUtils; +import java.net.URLDecoder; +import java.nio.charset.Charset; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +public class JsonObjectConverter implements Converter { + public JsonObject convert(String source) { + try { + source = URLDecoder.decode(source, Charset.defaultCharset()); + return McJsonUtils.toJsonElement(source).getAsJsonObject(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/midm/app/converter/UserAgentConverter.java b/src/main/java/com/midm/app/converter/UserAgentConverter.java new file mode 100644 index 0000000..e59b1ae --- /dev/null +++ b/src/main/java/com/midm/app/converter/UserAgentConverter.java @@ -0,0 +1,12 @@ +package com.midm.app.converter; + +import com.mitac.cell.internet.http.UserAgent; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +public class UserAgentConverter implements Converter { + public UserAgent convert(String source) { + return new UserAgent(source); + } +} diff --git a/src/main/java/com/midm/constant/GeneralConst.java b/src/main/java/com/midm/constant/GeneralConst.java new file mode 100644 index 0000000..f57053a --- /dev/null +++ b/src/main/java/com/midm/constant/GeneralConst.java @@ -0,0 +1,46 @@ +package com.midm.constant; + +public class GeneralConst { + public static final String KEY_KEY = "key"; + public static final String KEY_VALUE = "value"; + public static final String KEY_AUTH_KEY = "auth_key"; + public static final String KEY_ID = "id"; + public static final String KEY_NAME = "name"; + public static final String KEY_TITLE = "title"; + public static final String KEY_PHONE = "phone"; + public static final String KEY_MOBILE = "mobile"; + public static final String KEY_THEME = "theme"; + public static final String KEY_CONTENT = "content"; + public static final String KEY_SUMMARY = "summary"; + public static final String KEY_USER = "user"; + public static final String KEY_OWNER = "owner"; + public static final String DEFAULT = "default"; + public static final String HTML = ".html"; + public static final String CATEGORY_APP = "app"; + public static final String CATEGORY_GENERAL = "general"; + public static final String CATEGORY_OTA = "ota"; + public static final String CATEGORY_WEBAPP = "webapp"; + public static final String CATEGORY_OTHER = "other"; + public static final String CATEGORY_REPORT = "report"; + public static final String CATEGORY_FILE = "file"; + public static final String CATEGORY_DEVICE = "device"; + public static final String CATEGORY_SCREEN = "screen"; + public static final String CATEGORY_INSTALLED = "installed"; + public static final String CATEGORY_STORAGE = "storage"; + public static final String PROFILE = "profile"; + public static final String LOGO_LIGHT = "light"; + public static final String LOGO_DARK = "dark"; + public static final String FAVICON = "favicon"; + public static final String PROFILE_USERGROUP = "usergroup"; + public static final String PROFILE_ORGANIZATION = "org"; + public static final String PROFILE_SITE = "site"; + public static final String PROFILE_DEVICE_GROUP = "deviceGroup"; + public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L; + public static final String KEY_LANGUAGE = "language"; + public static final String KEY_DESC = "desc"; + public static final String KEY_DEVICE = "device"; + public static final String KEY_GROUP = "group"; + public static final String KEY_GROUPS = "groups"; + public static final String KEY_GROUP_UUID = "groupUuid"; + public static final String KEY_APP_FILE = "appFile"; +} diff --git a/src/main/java/com/midm/constant/LocaleConst.java b/src/main/java/com/midm/constant/LocaleConst.java new file mode 100644 index 0000000..7300036 --- /dev/null +++ b/src/main/java/com/midm/constant/LocaleConst.java @@ -0,0 +1,15 @@ +package com.midm.constant; + +import java.util.Locale; +import org.springframework.data.mongodb.core.query.Collation; + +public class LocaleConst { + public static final Locale DEFAULT_LOCALE; + public static final String EN_US = "en-US"; + public static final Collation COLLATION_DEFAULT; + + static { + DEFAULT_LOCALE = Locale.US; + COLLATION_DEFAULT = Collation.of(DEFAULT_LOCALE).strength(2); + } +} diff --git a/src/main/java/com/midm/constant/LocationConst.java b/src/main/java/com/midm/constant/LocationConst.java new file mode 100644 index 0000000..e74c499 --- /dev/null +++ b/src/main/java/com/midm/constant/LocationConst.java @@ -0,0 +1,8 @@ +package com.midm.constant; + +public class LocationConst { + public static String KEY_LAT = "lat"; + public static String KEY_LATITUDE = "latitude"; + public static String KEY_LON = "lon"; + public static String KEY_LONGITUDE = "longitude"; +} diff --git a/src/main/java/com/midm/constant/MidmConst.java b/src/main/java/com/midm/constant/MidmConst.java new file mode 100644 index 0000000..2f926e9 --- /dev/null +++ b/src/main/java/com/midm/constant/MidmConst.java @@ -0,0 +1,191 @@ +package com.midm.constant; + +public class MidmConst { + public static final String MIDM = "midm"; + public static final String KEY_REQUEST = "request"; + public static final String KEY_PARAMS = "params"; + public static final String KEY_ID = "_id"; + public static final String KEY_UUID = "uuid"; + public static final String KEY_EULA = "eula"; + public static final String KEY_SITE = "site"; + public static final String KEY_SITES = "sites"; + public static final String KEY_SITE_UUID = "siteUuid"; + public static final String KEY_SITE_HAS_BATTERY_PLAN = "hasBatteryPlan"; + public static final String KEY_GROUP_UUID = "groupUuid"; + public static final String KEY_PARENT_UUID = "parentUuid"; + public static final String KEY_ID_NAME = "idName"; + public static final String KEY_SITE_ID_NAME = "siteIdName"; + public static final String KEY_USER_UUID = "userUuid"; + public static final String KEY_DEVICE_UUID = "deviceUuid"; + public static final String KEY_DEVICE_SERIAL = "deviceSerial"; + public static final String KEY_DEVICE_PROFILE = "deviceProfile"; + public static final String KEY_RSA = "rsa"; + public static final String KEY_SERIALNO = "serialNo"; + public static final String KEY_TIMEZONE = "timeZone"; + public static final String KEY_WIFI_MAC = "wifiMac"; + public static final String KEY_FROM = "from"; + public static final String KEY_TO = "to"; + public static final String KEY_SELF_ENROLL = "selfEnroll"; + public static final String KEY_IF_EXISTS = "ifExists"; + public static final String KEY_RTC_ENABLED = "rtcEnabled"; + public static final String KEY_SOURCES = "sources"; + public static final String KEY_EMAIL = "email"; + public static final String KEY_ENABLE = "enable"; + public static final String KEY_ENABLED = "enabled"; + public static final String KEY_CLIENT_VERSION = "clientVersion"; + public static final String KEY_BATTERY_SERIAL = "batterySerial"; + public static final String KEY_BATTERY_CONDITION = "batteryCondition"; + public static final String KEY_COMMAND = "command"; + public static final String KEY_CATEGORY = "category"; + public static final String KEY_LOG = "log"; + public static final String KEY_LOGGED_AT = "loggedAt"; + public static final String KEY_INCLUDES = "includes"; + public static final String KEY_URL = "url"; + public static final String KEY_PATH = "path"; + public static final String KEY_ROOT = "root"; + public static final String KEY_OWNER = "owner"; + public static final String KEY_REGION = "region"; + public static final String KEY_MODEM = "modem"; + public static final String KEY_USER = "user"; + public static final String KEY_DEST = "dest"; + public static final String KEY_PUSH = "push"; + public static final String KEY_MOVE = "move"; + public static final String KEY_DELETE = "delete"; + public static final String KEY_EXTRACT = "extract"; + public static final String KEY_KEEP_IN_HOST = "keepInHost"; + public static final String KEY_IS_GLOBAL = "isGlobal"; + public static final String KEY_UPDATE_VIA = "update_via"; + public static final String KEY_SILENT_UPDATE = "silent_update"; + public static final String KEY_ALLOW_DOWNGRADE = "allow_downgrade"; + public static final String KEY_SHOW_PROGRESS = "show_progress"; + public static final String KEY_FORCE_TO_UPDATE = "force_to_update"; + public static final String KEY_REMOVE_AFTER_INSTALL = "remove_after_install"; + public static final String KEY_CREATED = "created"; + public static final String KEY_UPDATED = "updated"; + public static final String KEY_APPLIED = "applied"; + public static final String KEY_REPORTED_AT = "reportedAt"; + public static final String KEY_RESELLER = "reseller"; + public static final String KEY_RESELLER_SITE = "resellerSite"; + public static final String KEY_IS_RESELLER = "isReseller"; + public static final String KEY_DEVICE_LIMIT = "deviceLimit"; + public static final String KEY_LICENSE = "license"; + public static final String KEY_RENEW = "renew"; + public static final String KEY_AUTO_RENEW = "autoRenew"; + public static final String KEY_RENEW_TO_SAME_MODEL = "renewToSameModel"; + public static final String KEY_MODEL = "model"; + public static final String KEY_LICENSE_MODEL = "licenseModel"; + public static final String KEY_LICENSE_FEATURE = "licenseFeature"; + public static final String KEY_FEATURES = "features"; + public static final String KEY_PLAN = "plan"; + public static final String KEY_TARGET_PLAN = "targetPlan"; + public static final String KEY_SYSTEM = "system"; + public static final String KEY_STORE = "store"; + public static final String KEY_KEYSTORE = "keyStore"; + public static final String KEY_REPORT = "report"; + public static final String KEY_TEMP = "temp"; + public static final String KEY_DATE_TIME = "dateTime"; + public static final String KEY_HOUR_FORMAT = "hourFormat"; + public static final String KEY_ACTIVITY = "activity"; + public static final String KEY_AMOUNT = "amount"; + public static final String KEY_TOTAL = "total"; + public static final String KEY_FRESH = "fresh"; + public static final String KEY_FRESH_EXPIRING = "freshExpiring"; + public static final String KEY_USED = "used"; + public static final String KEY_USED_EXPIRING = "usedExpiring"; + public static final String KEY_ACTIVE = "active"; + public static final String KEY_INACTIVE = "inactive"; + public static final String KEY_EXPIRED = "expired"; + public static final String KEY_LICENSED = "licensed"; + public static final String KEY_MEMORY = "memory"; + public static final String KEY_BATTERY = "battery"; + public static final String KEY_LOCATION = "location"; + public static final String KEY_DATA_USAGE = "dataUsage"; + public static final String REQUEST_APPS = "apps"; + public static final String REQUEST_OTAS = "otas"; + public static final String REQUEST_FILES = "files"; + public static final String REQUEST_ENROLL = "enroll"; + public static final String REQUEST_DATA_USAGE = "data_usage"; + public static final String KEY_REPEAT_OPTION = "repeatOption"; + public static final String KEY_REPEAT_PERIOD = "repeatPeriod"; + public static final String KEY_REPEAT_EVERY = "repeatEvery"; + public static final String VALUE_HOST = "host"; + public static final String VALUE_DEVICE = "device"; + public static final String VALUE_WIFI = "wifi"; + public static final String VALUE_MOBILE = "mobile"; + public static final String VALUE_BOTH = "both"; + public static final String VALUE_ALL = "all"; + public static final String VALUE_SELECTED = "selected"; + public static final String TYPE_WIFI = "WIFI"; + public static final String TYPE_MOBILE = "MOBILE"; + public static final String VALUE_LOGO = "logo"; + public static final String VALUE_PROFILE = "profile"; + public static final String VALUE_BACKGROUND = "background"; + public static final int VALUE_DEFAULT_HEART_BEAT = 300; + public static final String KEY_WEBSOCKET_EXTENSION = "sec-websocket-extensions"; + public static final String REQUEST_UPDATE_PROFILE = "update_profile"; + public static final int CODE_UPDATE_PROFILE = 131; + public static final String REQUEST_UPDATE_ALL_PROFILES = "update_profile_all"; + public static final int CODE_UPDATE_ALL_PROFILES = 132; + public static final String REQUEST_SYNC_PROFILE = "sync_profile"; + public static final int CODE_SYNC_PROFILE = 136; + public static final String REQUEST_REMOVE_PROFILE = "remove_profile"; + public static final int CODE_REMOVE_PROFILE = 136; + public static final String KEY_THEME = "theme"; + public static final String KEY_NOTIFICATION = "noti"; + public static final String KEY_COUNT = "count"; + public static final String KEY_PAGE = "page"; + public static final String KEY_EXPIRY = "expiry"; + public static final String KEY_LICENSE_EXPIRY = "licenseExpiry"; + public static final String KEY_FINAL_EXPIRY = "finalExpiry"; + public static final String KEY_ACTIVATED_AT = "activatedAt"; + public static final String KEY_ACTIVATION_COUNT = "activationCount"; + public static final String KEY_CHILD_SITE = "childSite"; + public static final String KEY_URL_EXPIRY = "urlExpiry"; + public static final String KEY_ICON_EXPIRY = "iconExpiry"; + public static final String KEY_EXPIRED_IN_10 = "expiredIn10"; + public static final String KEY_EXPIRED_IN_30 = "expiredIn30"; + public static final String KEY_EXPIRED_IN_45 = "expiredIn45"; + public static final String KEY_EXPIRED_IN_45_WITH_AUTO_RENEW = "expiredIn45WithAutoRenew"; + public static final String KEY_FOR_WHAT = "forWhat"; + public static final String KEY_REFERENCE = "reference"; + public static final String KEY_LOGGER = "logger"; + public static final String KEY_INSTALL = "install"; + public static final String KEY_INSTALL_APPS = "installApps"; + public static final String KEY_SHOW = "show"; + public static final String KEY_MSETTINGS = "msettings"; + public static final String KEY_WALLPAPER = "wallpaper"; + public static final String PLAN_STANDARD_BATTERYPRO = "standardWithBatteryPro"; + public static final String PLAN_STANDARD = "standard"; + public static final String PLAN_LITE = "lite"; + public static final String KEY_ERROR = "error"; + public static final String KEY_PAGE_FOR = "pageFor"; + public static final String KEY_HAS_USER = "hasUser"; + public static final String KEY_IP = "ip"; + public static final String KEY_IP_ADDR = "ip_addr"; + public static final String KEY_PUBLIC_IP = "public_ip"; + public static final String KEY_ADD = "add"; + public static final String KEY_REMOVE = "remove"; + public static final String KEY_PO = "po"; + public static final String KEY_NOTE = "note"; + public static final String KEY_NOTES = "notes"; + public static final String KEY_SETTINGS = "settings"; + public static final String KEY_PROFILES = "profiles"; + public static final String KEY_STATUS = "status"; + public static final String STATUS_ADDED = "added"; + public static final String STATUS_REPLACED = "replaced"; + public static final String STATUS_REMOVED = "removed"; + public static final String VALUE_UNKNOWN = "unknown"; + public static final String VALUE_NONE = "none"; + public static final String VALUE_NEVER = "never"; + public static final String VALUE_DISABLED = "disabled"; + public static final String VALUE_ONCE = "once"; + public static final String VALUE_BLOCKED = "blocked"; + public static final String VALUE_MITAC = "mitac"; + public static final String PACKAGE_MIDM_CLIENT = "com.mitac.midm.client"; + public static final String PACKAGE_MIDM_SYSTEM = "com.mitac.midm.system"; + public static final String PACKAGE_MILOCK = "com.mitac.milock"; + public static final String PACKAGE_MIBATTERY = "com.mitac.utils.battery"; + public static final String COLLECTION_MIDM_LOG = "midmLog"; + public static final String COLLECTION_DEVICE_REPORT = "deviceReport"; + public static final String COLOR_RED = "red"; +} diff --git a/src/main/java/com/midm/constant/PropertyConst.java b/src/main/java/com/midm/constant/PropertyConst.java new file mode 100644 index 0000000..a743f27 --- /dev/null +++ b/src/main/java/com/midm/constant/PropertyConst.java @@ -0,0 +1,93 @@ +package com.midm.constant; + +public class PropertyConst { + public static final String CATEGORY_HADRWARE = "hardware_info"; + public static final String CATEGORY_SOFTWARE_INFO = "software_info"; + public static final String CATEGORY_NETWORK = "network"; + public static final String CATEGORY_SHIPMENT = "shipment"; + public static final String CATEGORY_EVENT = "event"; + public static final String CATEGORY_ACTIVITY = "activity"; + public static final String CATEGORY_UPDATE = "update"; + public static final String ROLE = "role"; + public static final String ADMIN = "admin"; + public static final String ADMINISTRATOR = "Administrator"; + public static final String NAME = "name"; + public static final String NATIONAL_ID = "nationalId"; + public static final String GENDER = "gender"; + public static final String COMMENT = "comment"; + public static final String MEMO = "memo"; + public static final String EMAIL = "email"; + public static final String LOGIN_ID = "loginId"; + public static final String PASSWORD = "password"; + public static final String PROPERTIES = "properties"; + public static final String USER_PROPERTIES = "userProperties"; + public static final String REGISTER_PROPERTIES = "registerProperties"; + public static final String KEEP_SIGNIN = "keepSignIn"; + public static final String LAST_SITE = "lastSite"; + public static final String LAST_PAGE = "lastPage"; + public static final String DEPARTMENT = "dept"; + public static final String PLACE = "place"; + public static final String REFERENCE = "reference"; + public static final String POST_FROM = "postFrom"; + public static final String POST_TO = "postTo"; + public static final String DOCUMENT_NO = "doc_no"; + public static final String UPDATE = "update"; + public static final String SERIAL_NO = "serial_no"; + public static final String PART_NO = "part_no"; + public static final String PALLET_NO = "pallet_mo"; + public static final String CARTON_SN = "carton_no"; + public static final String ACTIVE = "active"; + public static final String WIFI = "wifi"; + public static final String WIFI_MAC = "wifi_mac"; + public static final String MAC_ADDRESS = "mac_address"; + public static final String SKU_ID = "sku_id"; + public static final String COMPATIBLE_SKUS = "compatibleSkus"; + public static final String DEVICE_ID = "deviceId"; + public static final String SSID = "ssid"; + public static final String TELEPHONY = "telephony"; + public static final String PRODUCT_ID = "product_id"; + public static final String PRODUCT_MODEL = "product_model"; + public static final String BUILD_NO = "build_no"; + public static final String DISPLAY_ID = "display_id"; + public static final String PRODUCT_DISPLAY_ID = "product_display_id"; + public static final String PRE_DISPLAY_ID = "preDisplayId"; + public static final String BUILD_DATE = "build_date"; + public static final String REGION_VERSION = "region_version"; + public static final String REGION_BUILD_DATE = "region_build_date"; + public static final String CUSTOMER_ID = "customer_id"; + public static final String ACTIVE_NETWORK = "active_network"; + public static final String SDK_VERSION = "sdk_version"; + public static final String SCRIPT_VERSION = "script_version"; + public static final String RELEASE_VERSION = "release_version"; + public static final String OS_VERSION = "os_version"; + public static final String GMS_AVAILABLE = "gms_available"; + public static final String TYPE = "type"; + public static final String PRE_BUILD = "preBuild"; + public static final String POST_BUILD = "postBuild"; + public static final String STATE = "state"; + public static final String IS_ONLINE = "isOnline"; + public static final String STATE_REGISTERED = "registered"; + public static final String STATE_ENROLLED = "enrolled"; + public static final String STATE_RETIRED = "retired"; + public static final String FILE_URL = "fileUrl"; + public static final String ICON_URL = "iconUrl"; + public static final String SETTINGS_HEARTBEAT_INTERVAL = "websocket.heartbeat.interval"; + public static final String MESSAGE = "message"; + public static final String FILE_NAME = "fileName"; + public static final String FILE_LENGTH = "fileLength"; + public static final String PACKAGE = "package"; + public static final String PACKAGE_NAME = "packageName"; + public static final String LABEL = "label"; + public static final String VERSION_CODE = "versionCode"; + public static final String VERSION_NAME = "versionName"; + public static final String CHECKSUM = "checksum"; + public static final String CERT_MD5 = "certMd5"; + public static final String STORAGES = "storages"; + public static final String MEMORY = "memory"; + public static final String BATTERY = "battery"; + public static final String TEMPERATURE = "temperature"; + public static final String VOLTAGE = "voltage"; + public static final String CHARGE_LEVEL = "level"; + public static final String CHARGING_STATUS = "charginStatus"; + public static final String PLUGGED = "plugged"; +} diff --git a/src/main/java/com/midm/controller/BaseController.java b/src/main/java/com/midm/controller/BaseController.java new file mode 100644 index 0000000..d6a6697 --- /dev/null +++ b/src/main/java/com/midm/controller/BaseController.java @@ -0,0 +1,82 @@ +package com.midm.controller; + +import com.google.common.base.Strings; +import com.midm.model.org.User; +import com.midm.security.UserPrincipal; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.LocaleService; +import com.mitac.cell.utils.McStringUtils; +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.web.servlet.LocaleResolver; + +public class BaseController { + @Autowired + protected LocaleResolver localeResolver; + @Autowired + protected LocaleService localeService; + @Autowired + protected UserService userService; + @Autowired + protected SiteService siteService; + protected User user = null; + protected String theme = "default"; + + protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + this.init(request, response, authentication, (String)null); + } + + protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication, String localeTag) { + this.determineUser(request, authentication); + String userLocale = !Strings.isNullOrEmpty(localeTag) ? localeTag : (this.user != null ? this.user.getSettingAsString("language") : request.getLocale().toLanguageTag()); + if (McStringUtils.isNullOrEmpty(userLocale)) { + userLocale = request.getLocale().toLanguageTag(); + } + + Locale altLocale = this.localeService.findAltLocale(userLocale); + if (this.user != null) { + String altLocaleTag = altLocale.toLanguageTag(); + if (userLocale == null || !this.user.isSameLocale(altLocaleTag)) { + this.userService.changeLocale(this.user, altLocaleTag); + } + } + + this.localeResolver.setLocale(request, response, altLocale); + } + + protected String getView(Authentication authentication, String viewName) { + return this.getResource(authentication, viewName + ".html"); + } + + protected String getResource(Authentication authentication, String fileName) { + User user = UserPrincipal.getUser(authentication); + String theme = user == null ? "default" : user.getTheme(); + return theme + fileName; + } + + protected String getTemplateResource(Authentication authentication, String fileName) { + if (this.user == null) { + this.user = UserPrincipal.getUser(authentication); + } + + String theme = this.user == null ? "default" : this.user.getTheme(); + return "templates/" + theme + fileName; + } + + private void determineUser(HttpServletRequest request, Authentication authentication) { + if (authentication != null) { + synchronized(authentication) { + this.user = UserPrincipal.getUser(authentication); + this.theme = this.user != null ? this.user.getTheme() : "default"; + } + } else { + this.user = null; + this.theme = "default"; + } + + } +} diff --git a/src/main/java/com/midm/controller/DeviceController.java b/src/main/java/com/midm/controller/DeviceController.java new file mode 100644 index 0000000..8a51611 --- /dev/null +++ b/src/main/java/com/midm/controller/DeviceController.java @@ -0,0 +1,236 @@ +package com.midm.controller; + +import com.midm.model.device.Device; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.model.org.UserToken; +import com.midm.service.device.DeviceService; +import com.midm.service.message.WebSocketSessionManager; +import com.mitac.cell.internet.http.McRequest; +import com.mitac.cell.utils.McUuidUtils; +import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.servlet.view.RedirectView; + +/** + * ====================================================================================== + * 移动终端设备远程接入与控制路由控制器 (DeviceController) + * ====================================================================================== + * + *

【架构设计与安全亮点】 + * 1. 业务场景: + * - 管理员在监控大屏或告警邮件中点击设备远程查看链接,一键无感知跳转至设备的远程桌面或管理详情; + * - 设备维护人员使用移动端或外链进行快速应急远程排障(Remote Assist)。 + * 2. 【安全机制一:一次性动态安全令牌 (OTT - One-Time Token)】: + * - 在 `GET /device/{accessToken}` 中,Token 经 Base64 编码,且类型标记为 'D'(Device Token); + * - 验证通过后**立即从数据库中物理删除**({@link #remoteView} 第 56 行),从根源杜绝重放攻击(Replay Attack); + * - 严格校验 Token 是否过期(isExpired)以及租户数据隔离边界。 + * 3. 【安全机制二:多租户 RBAC 权限与版本授权控制】: + * - 严格校验操作人是否归属于设备所在租户(Site); + * - 校验用户角色是否拥有 `DEVICE_MANAGE_ROLES` 权限; + * - 针对租户订阅版本(如基础版 Lite vs 企业版 Pro),对高级功能标签页(如 WebRTC 远程控制 remoteControl、GPS实时轨迹 location)进行动态降级限制。 + * + * @author MiDM Core Platform Team + */ +@Controller +public class DeviceController extends BaseController { + + /** 设备详情页支持的功能标签页集合 */ + private static List tabs = Arrays.asList("general", "remoteControl", "apps", "files", "location", "logs"); + + @Autowired + private DeviceService deviceService; + + @Autowired + private WebSocketSessionManager sessionManager; + + /** + * 【安全快捷通道】基于一次性动态 Token 的设备远程控制接入接口 + * + * @param request HTTP 请求 + * @param response HTTP 响应 + * @param authentication 当前 Spring Security 认证上下文 + * @param model 视图模型 + * @param accessToken Base64 编码的一次性设备访问令牌 + * @param language 国际化语言(默认 "en-US") + * @param tab 目标定位标签页(如 "remoteControl" 远程桌面、"location" GPS轨迹,默认 "general") + * @return 重定向到单页面应用前端详情路由的 RedirectView + * @throws IOException 网络 IO 异常 + */ + @RequestMapping( + value = {"/device/{accessToken}"}, + method = {RequestMethod.GET} + ) + public RedirectView remoteView(HttpServletRequest request, HttpServletResponse response, + Authentication authentication, Model model, + @PathVariable String accessToken, + @RequestParam(required = false, defaultValue = "en-US") String language, + @RequestParam(required = false, defaultValue = "general") String tab) throws IOException { + + // 1. 获取当前会话登录的用户身份 + User loggedUser = this.userService.authorizedUser(authentication, (String)null); + if (authentication != null) { + UserToken prevToken = (UserToken)authentication.getCredentials(); + if (!this.userService.existsById(UserToken.class, prevToken)) { + this.logout(loggedUser); + } + } + + // 2. 解码并反序列化 Token UUID + accessToken = URLDecoder.decode(accessToken, Charset.defaultCharset()); + UUID tokenUuid = McUuidUtils.toUuidFromBase64(accessToken); + UserToken deviceToken = this.userService.findToken(tokenUuid); + + // 3. 安全性严格校验:必须存在且类型为 'D' (Device Token),且未过期 + if (deviceToken != null && deviceToken.getTokenType() == 'D' && !deviceToken.isExpired()) { + // 【核心安全点:一次性销毁防重放】 + this.userService.delete(deviceToken); + + UUID requesterUuid = deviceToken.getUserUuid(); + // 若当前登录人与发券人不一致,先清除旧会话 + if (loggedUser != null && !loggedUser.getUuid().equals(requesterUuid)) { + this.logout(loggedUser); + loggedUser = null; + } + + // 自动为请求发起者建立登录认证态 + if (loggedUser == null) { + loggedUser = this.userService.findUserByUserUuid(requesterUuid); + authentication = this.userService.authorizeLogin(loggedUser); + } + + loggedUser.setProfile("forRemote", true); + this.init(request, response, authentication, language); + + // 4. 定位目标设备(优先在线实例)并校验租户归属隔离 + UUID deviceUuid = deviceToken.getDeviceUuid(); + Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid); + if (device != null && this.user.isBelongedToSite(device.getSiteUuid())) { + if (!tabs.contains(tab)) { + tab = "general"; + } + + // 5. 商业版本功能门限鉴权:若租户为 Lite 简版且未购买该功能,强制降级到概要标签 + Site site = this.siteService.findByUuid(device.getSiteUuid()); + if (!tab.equals("general") && site.isLite() && !site.isFeatureAllowed("device", tab)) { + tab = "general"; + } + + // 跳转前端对应功能视图 + return this.remoteView(request, device, tab); + } else { + this.logout(loggedUser); + response.sendError(401); + return null; + } + } else { + response.sendError(400, "The remote control URL is unavailable."); + if (authentication != null) { + this.logout(loggedUser); + } + return null; + } + } + + /** + * 【凭证直连通道】基于企业邮箱、密码/凭证和设备序列号直接接入远程管理 + */ + @RequestMapping( + value = {"/device/{email}/{credential}/{serialNo}"}, + method = {RequestMethod.GET} + ) + public RedirectView remoteView(HttpServletRequest request, HttpServletResponse response, + Authentication authentication, Model model, + @PathVariable String email, + @PathVariable String credential, + @PathVariable String serialNo, + @RequestParam(required = false, defaultValue = "en-US") String language, + @RequestParam(required = false, defaultValue = "general") String tab) throws IOException { + + // 1. 查找目标硬件设备 + Device device = this.deviceService.findBySerialNo(serialNo); + if (device == null) { + this.logout(this.user); + response.sendError(401, "The device may not exist."); + return null; + } else { + Site site = this.siteService.findByUuid(device.getSiteUuid()); + User user = this.userService.authorizedUser(authentication, (String)null); + if (user != null && !user.getEmail().equals(email)) { + this.logout(user); + user = null; + } + + // 2. 校验用户身份合法性 + if (user == null) { + user = this.userService.findUserByEmail(site.getUuid(), email); + if (user == null || !user.getEnabled() || !user.isBelongedToSite(site)) { + response.sendError(401, "The account may not exist or disabled or not belonged to the site."); + return null; + } + } + + authentication = this.userService.updateAuthorizedUser(user); + + // 3. 校验设备管理角色权限 + if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + this.logout(user); + response.sendError(401, "The user doesn't have the role to manage the device."); + return null; + } else if (site != null && (site.isCredentialMatched(credential) || this.userService.matchPassword(user, credential))) { + // 4. 凭证比对成功 + if (!tabs.contains(tab)) { + tab = "general"; + } + + if (!tab.equals("general") && site.isLite() && !site.isFeatureAllowed("device", tab)) { + tab = "general"; + } + + user.setProfile("forRemote", true); + this.init(request, response, authentication, language); + return this.remoteView(request, device, tab); + } else { + response.sendError(401, "The site credential or password is mismatched."); + return null; + } + } + } + + /** + * 安全退出并彻底销毁会话与 SecurityContext + */ + private void logout(User loggedUser) { + if (loggedUser != null) { + this.sessionManager.logout(loggedUser); + SecurityContextHolder.getContext().setAuthentication((Authentication)null); + this.userService.deleteLoginToken(loggedUser); + } + } + + /** + * 构建单页面应用前端重定向路由地址 + */ + private RedirectView remoteView(HttpServletRequest request, Device device, String tab) { + String url = McRequest.getBaseUrl(request, String.format("#/device/details/%s/%s/%s", device.getUuid(), device.getSerialNo(), tab)); + url = URLDecoder.decode(url, Charset.defaultCharset()); + RedirectView view = new RedirectView(url); + return view; + } +} diff --git a/src/main/java/com/midm/controller/ExceptionController.java b/src/main/java/com/midm/controller/ExceptionController.java new file mode 100644 index 0000000..ef31055 --- /dev/null +++ b/src/main/java/com/midm/controller/ExceptionController.java @@ -0,0 +1,123 @@ +package com.midm.controller; + +import com.google.common.base.Strings; +import com.mitac.cell.utils.McStringUtils; +import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.Charset; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +public class ExceptionController extends BaseController implements ErrorController { + @RequestMapping( + value = {"error"}, + method = {RequestMethod.GET} + ) + public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "JSESSIONID",defaultValue = "") String sessionId, Model model, @RequestParam(required = false) String language) { + int errorCode = (Integer)request.getAttribute("javax.servlet.error.status_code"); + if (!Strings.isNullOrEmpty(sessionId)) { + this.init(request, (HttpServletResponse)null, authentication, language); + String contextPath = (String)request.getAttribute("javax.servlet.forward.context_path"); + String path = (String)request.getAttribute("javax.servlet.error.request_uri"); + if (errorCode == 404) { + if (authentication == null) { + return "redirect:/"; + } else { + String route = path.substring(contextPath.length()); + return "forward:/#" + route; + } + } else { + Error error = new Error(errorCode); + String message = (String)request.getAttribute("javax.servlet.error.message"); + if (!Strings.isNullOrEmpty(message)) { + error.setMessage(message); + } + + Exception ex = (Exception)request.getAttribute("javax.servlet.error.exception"); + if (ex != null) { + error.setException(ex); + } + + model.addAttribute("path", path); + model.addAttribute("error", error); + String stackTrace = McStringUtils.stackTrace(ex); + model.addAttribute("stackTrace", stackTrace); + return this.getView(authentication, "/error"); + } + } else { + try { + response.sendError(errorCode); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } + } + + @RequestMapping({"generate_204", "gen_204"}) + public void gen204(HttpServletRequest request, HttpServletResponse response) { + try { + response.sendError(204); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + @RequestMapping( + value = {"blocked"}, + method = {RequestMethod.GET} + ) + public String blocked(HttpServletRequest request, Authentication authentication, Model model, @RequestParam(required = false) String url, @RequestParam(required = false) String serialNo, @RequestParam(required = false) String language) { + this.init(request, (HttpServletResponse)null, authentication, language); + model.addAttribute("url", URLDecoder.decode(url, Charset.defaultCharset())); + model.addAttribute("serialNo", serialNo); + Error error = new Error(408); + model.addAttribute("error", error); + return this.getView(authentication, "/error"); + } + + private class Error { + private int code; + private Exception exception; + private String message; + + public Error(int code) { + this.setCode(code); + } + + public int getCode() { + return this.code; + } + + public void setCode(int code) { + this.code = code; + } + + public Exception getException() { + return this.exception; + } + + public void setException(Exception exception) { + this.exception = exception; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } + } +} diff --git a/src/main/java/com/midm/controller/FragmentController.java b/src/main/java/com/midm/controller/FragmentController.java new file mode 100644 index 0000000..72f8abd --- /dev/null +++ b/src/main/java/com/midm/controller/FragmentController.java @@ -0,0 +1,79 @@ +package com.midm.controller; + +import java.util.Locale; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +public class FragmentController extends BaseController { + @RequestMapping( + value = {"/view/**"}, + method = {RequestMethod.GET} + ) + public String view(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Model model) { + this.init(request, response, authentication); + model.addAttribute("theme", this.theme); + if (authentication == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + } + + return this.getView(authentication, request.getServletPath()); + } + + @RequestMapping( + value = {"/view/system/resource"}, + method = {RequestMethod.GET} + ) + public String resourceView(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @RequestParam String category) { + super.init(request, response, authentication); + model.addAttribute("category", category); + return "template/system/resource.html"; + } + + @RequestMapping( + value = {"/fragment/{fragmentName}"}, + method = {RequestMethod.GET} + ) + public String fragment(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String fragmentName) { + super.init(request, response, authentication); + model.addAttribute("theme", this.theme); + if (authentication == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + } + + String var10000 = this.getView(authentication, request.getServletPath()); + return var10000 + " :: fragment"; + } + + @RequestMapping( + value = {"/fragment/{fragmentName}/{blockName}"}, + method = {RequestMethod.GET} + ) + public String fragment(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String fragmentName, @PathVariable String blockName) { + super.init(request, response, authentication); + String var10000 = this.getView(authentication, "/fragment/" + fragmentName); + return var10000 + " :: " + blockName; + } + + @RequestMapping( + value = {"/dialog/{dialogName}"}, + method = {RequestMethod.GET} + ) + public String dialog(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String dialogName, @RequestParam(required = false) String category) { + this.init(request, response, authentication); + model.addAttribute("theme", this.theme); + if (authentication == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + } + + String var10000 = this.getView(authentication, request.getServletPath()); + return var10000 + " :: dialog"; + } +} diff --git a/src/main/java/com/midm/controller/HomeController.java b/src/main/java/com/midm/controller/HomeController.java new file mode 100644 index 0000000..90c253b --- /dev/null +++ b/src/main/java/com/midm/controller/HomeController.java @@ -0,0 +1,273 @@ +package com.midm.controller; + +import com.google.common.base.Strings; +import com.midm.model.org.Site; +import com.midm.model.org.UserToken; +import com.midm.security.UserPrincipal; +import com.mitac.cell.internet.http.McResponse; +import java.io.IOException; +import java.util.UUID; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.servlet.view.RedirectView; + +@Controller +public class HomeController extends BaseController { + @RequestMapping( + value = {"/", "/index.html"}, + method = {RequestMethod.GET} + ) + public String home(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, @CookieValue(value = "site.uuid",defaultValue = "") UUID siteUuid, @CookieValue(value = "locale",defaultValue = "en-US") String locale, Model model, @RequestHeader("host") String hostName, @RequestParam(required = false) String language, @RequestParam(required = false) String siteId) { + if (Strings.isNullOrEmpty(language)) { + language = locale; + } + + if (authentication != null) { + UserToken token = (UserToken)authentication.getCredentials(); + UserToken existingToken = token == null ? null : this.userService.findToken(token.getTokenUuid()); + if (existingToken == null) { + SecurityContextHolder.getContext().setAuthentication((Authentication)null); + authentication = null; + if (token != null && token.getTokenUuid().equals(tokenUuid)) { + tokenUuid = null; + McResponse.setCookie(response, "user.token", (String)null); + } + } + } + + this.init(request, response, authentication, language); + model.addAttribute("theme", this.theme); + if (authentication == null && tokenUuid != null) { + UserToken token = this.userService.findToken(tokenUuid); + if (token != null) { + authentication = this.userService.authorizeLogin(tokenUuid); + } else { + McResponse.setCookie(response, "user.token", (String)null); + } + } + + if (authentication == null) { + if (!Strings.isNullOrEmpty(siteId)) { + Site site = siteId.equals("default") ? null : this.siteService.findByIdName(siteId); + if (site != null) { + siteUuid = site.getUuid(); + model.addAttribute("siteUuid", siteUuid); + McResponse.setCookie(response, "site.uuid", siteUuid.toString()); + } else { + siteUuid = null; + } + } + + if (siteUuid != null) { + model.addAttribute("siteUuid", siteUuid); + } + + model.addAttribute("hasUser", this.userService.hasUser()); + model.addAttribute("pageFor", "login"); + model.addAttribute("locale", language); + if (locale != null && language != null && !locale.equals(language)) { + McResponse.setCookie(response, "locale", language); + } + + return this.getView(authentication, "/login"); + } else { + this.user = UserPrincipal.getUser(authentication); + if (this.user == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + model.addAttribute("pageFor", "login"); + model.addAttribute("locale", language); + if (locale != null && language != null && !locale.equals(language)) { + McResponse.setCookie(response, "locale", language); + } + + return this.getView(authentication, "/login"); + } else { + return this.getView(authentication, "/index"); + } + } + } + + @RequestMapping( + value = {"/remoteLogout"}, + method = {RequestMethod.GET} + ) + public String home(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Model model, @RequestParam(required = false) String language) { + this.init(request, response, authentication, language); + model.addAttribute("theme", this.theme); + return this.getView(authentication, "/remoteLogout"); + } + + @RequestMapping( + value = {"/"}, + method = {RequestMethod.POST} + ) + public void homePost(HttpServletRequest request, HttpServletResponse response) { + try { + response.sendError(400); + } catch (IOException var4) { + } + + } + + @RequestMapping( + value = {"register"}, + method = {RequestMethod.GET} + ) + public String registerToModelSite(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, @RequestParam String modelSite, ModelMap model, @RequestParam(required = false) String language) { + this.init(request, response, authentication, language); + model.addAttribute("theme", this.theme); + UserToken token = null; + if (authentication == null && tokenUuid != null) { + token = this.userService.findToken(tokenUuid); + authentication = this.userService.authorizeLogin(tokenUuid); + } + + if (authentication == null && token == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + model.addAttribute("pageFor", "register"); + return this.getView(authentication, "/login"); + } else { + return "forward:/"; + } + } + + @RequestMapping( + value = {"{modelSite}/register"}, + method = {RequestMethod.GET} + ) + public RedirectView redirectToRegister(ModelMap model, @PathVariable String modelSite, @RequestParam(required = false) String language) { + model.clear(); + return new RedirectView("../register?modelSite=" + modelSite); + } + + @RequestMapping( + value = {"/bypass", "/dpc"}, + method = {RequestMethod.GET} + ) + public String bypassMode(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, ModelMap model, @RequestParam(required = false) String language, @RequestHeader("host") String hostName) { + this.init(request, response, authentication, language); + model.addAttribute("theme", this.theme); + UserToken token = null; + if (authentication == null && tokenUuid != null) { + token = this.userService.findToken(tokenUuid); + authentication = this.userService.authorizeLogin(tokenUuid); + } + + if (authentication == null && token == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + model.addAttribute("pageFor", "dpc"); + return this.getView(authentication, "/login"); + } else { + this.user = UserPrincipal.getUser(authentication); + if (this.user.getSettingAsBoolean("keepSignIn")) { + if (token == null && authentication != null) { + token = (UserToken)authentication.getCredentials(); + } + + if (token != null) { + Cookie cookie = new Cookie("user.token", token.getTokenUuid().toString()); + response.addCookie(cookie); + } + } else { + Cookie cookie = new Cookie("user.token", (String)null); + response.addCookie(cookie); + } + + return this.getView(authentication, "/index"); + } + } + + @RequestMapping( + value = {"{modelSite}/bypass", "{modelSite}/dpc"}, + method = {RequestMethod.GET} + ) + public String bypassModeWithModel(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, ModelMap model, @RequestParam(required = false) String language, @RequestHeader("host") String hostName) { + this.init(request, response, authentication, language); + model.addAttribute("theme", this.theme); + UserToken token = null; + if (authentication == null && tokenUuid != null) { + token = this.userService.findToken(tokenUuid); + authentication = this.userService.authorizeLogin(tokenUuid); + } + + if (authentication == null && token == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + model.addAttribute("pageFor", "dpc"); + return this.getView(authentication, "/login"); + } else { + this.user = UserPrincipal.getUser(authentication); + if (this.user.getSettingAsBoolean("keepSignIn")) { + if (token == null && authentication != null) { + token = (UserToken)authentication.getCredentials(); + } + + if (token != null) { + Cookie cookie = new Cookie("user.token", token.getTokenUuid().toString()); + response.addCookie(cookie); + } + } else { + Cookie cookie = new Cookie("user.token", (String)null); + response.addCookie(cookie); + } + + return this.getView(authentication, "/index"); + } + } + + @RequestMapping( + value = {"/requestTrial"}, + method = {RequestMethod.GET} + ) + public String requestTrial(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(value = "user.token",defaultValue = "") UUID tokenUuid, ModelMap model, @RequestParam(required = false) String language, @RequestHeader("host") String hostName) { + this.init(request, response, authentication, language); + model.addAttribute("theme", this.theme); + UserToken token = null; + if (authentication == null && tokenUuid != null) { + token = this.userService.findToken(tokenUuid); + authentication = this.userService.authorizeLogin(tokenUuid); + } + + if (authentication == null && token == null) { + model.addAttribute("hasUser", this.userService.hasUser()); + model.addAttribute("pageFor", "requestTrial"); + return this.getView(authentication, "/login"); + } else { + this.user = UserPrincipal.getUser(authentication); + if (this.user.getSettingAsBoolean("keepSignIn")) { + if (token == null && authentication != null) { + token = (UserToken)authentication.getCredentials(); + } + + if (token != null) { + Cookie cookie = new Cookie("user.token", token.getTokenUuid().toString()); + response.addCookie(cookie); + } + } else { + Cookie cookie = new Cookie("user.token", (String)null); + response.addCookie(cookie); + } + + return this.getView(authentication, "/index"); + } + } + + @RequestMapping( + method = {RequestMethod.OPTIONS, RequestMethod.GET}, + path = {"/login/{siteId}"} + ) + public String forwardToLogin(@PathVariable String siteId) { + return "redirect:/?siteId=" + siteId; + } +} diff --git a/src/main/java/com/midm/controller/UserController.java b/src/main/java/com/midm/controller/UserController.java new file mode 100644 index 0000000..19f3098 --- /dev/null +++ b/src/main/java/com/midm/controller/UserController.java @@ -0,0 +1,60 @@ +package com.midm.controller; + +import com.midm.model.org.User; +import com.midm.model.org.UserToken; +import com.mitac.cell.utils.McUuidUtils; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.server.NotAcceptableStatusException; + +@Controller +public class UserController extends BaseController { + @RequestMapping( + value = {"/resetPassword"}, + method = {RequestMethod.GET} + ) + public String home(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Model model, @RequestParam(name = "token") String passwordTokenUid, @RequestParam(required = false) String language) { + this.init(request, response, authentication, language); + model.addAttribute("theme", this.theme); + UUID passwordTokenUuid = McUuidUtils.toUuidFromBase64(passwordTokenUid); + UserToken token = this.userService.findToken(passwordTokenUuid); + if (token != null && token.isExpired()) { + this.userService.deleteTokenByType(token); + } + + if (token != null && token.getTokenType() == 'P') { + model.addAttribute("error", false); + User user = this.userService.findUserByUserUuid(token.getUserUuid()); + model.addAttribute("token", token); + model.addAttribute("user", user); + return this.getView(authentication, "/resetPassword"); + } else { + model.addAttribute("error", true); + return this.getView(authentication, "/resetPassword"); + } + } + + @RequestMapping( + value = {"/keepSession"}, + method = {RequestMethod.GET}, + produces = {"text/plain"} + ) + @ResponseBody + public String getSettings(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + throw new NotAcceptableStatusException(""); + } else { + return "ok"; + } + } +} diff --git a/src/main/java/com/midm/controller/lib/BarcodeController.java b/src/main/java/com/midm/controller/lib/BarcodeController.java new file mode 100644 index 0000000..6945f69 --- /dev/null +++ b/src/main/java/com/midm/controller/lib/BarcodeController.java @@ -0,0 +1,21 @@ +package com.midm.controller.lib; + +import com.mitac.cell.barcode.QrCode; +import com.mitac.cell.io.McResource; +import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +public class BarcodeController { + @RequestMapping( + value = {"/barcode/qr/{code}"}, + method = {RequestMethod.GET} + ) + public void qrCode(HttpServletResponse response, @PathVariable String code, @RequestParam(required = false) Integer size, @RequestParam(required = false) Integer margin, @RequestParam(required = false) Boolean encrypt) { + McResource.copyToResponse(response, QrCode.toImage(code, size, margin)); + } +} diff --git a/src/main/java/com/midm/controller/lib/FilesController.java b/src/main/java/com/midm/controller/lib/FilesController.java new file mode 100644 index 0000000..5d2120c --- /dev/null +++ b/src/main/java/com/midm/controller/lib/FilesController.java @@ -0,0 +1,598 @@ +package com.midm.controller.lib; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.common.io.Files; +import com.midm.model.device.Device; +import com.midm.model.file.AppFile; +import com.midm.model.file.BaseFile; +import com.midm.model.org.User; +import com.midm.security.UserPrincipal; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.DeviceService; +import com.midm.service.file.FileService; +import com.midm.service.file.ReportService; +import com.midm.service.store.StoreAppService; +import com.midm.service.store.StoreOtaService; +import com.midm.service.store.StoreOtherService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.io.McResource; +import com.mitac.cell.utils.McUrlUtils; +import java.io.File; +import java.io.IOException; +import java.util.UUID; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.HandlerMapping; + +@Controller +public class FilesController { + @Autowired + private ServletContext servletContext; + @Autowired + private FileService fileService; + @Autowired + private StoreAppService storeAppService; + @Autowired + private StoreOtaService storeOtaService; + @Autowired + private DeviceService deviceService; + @Autowired + private ReportService reportService; + @Autowired + private StoreOtherService storeOtherService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"userfile/{userUuid}/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getUserFile(HttpServletResponse response, Authentication authentication, @PathVariable UUID userUuid, @PathVariable UUID fileUuid, @PathVariable String fileName, @RequestParam(required = false) Long position, @RequestParam(required = false) Long crc32) { + String filePath = this.fileService.getUserFilePath(userUuid, fileUuid); + McFile file = new McFile(filePath); + McResource.copyFileToResponse(this.servletContext, response, file, fileName, 0, -1); + file.delete(); + } + + @RequestMapping( + value = {"file/device/{deviceUuid}/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void geDevicetFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID deviceUuid, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String filePath = this.fileService.getDeviceFilePath(user.getSiteUuid(), deviceUuid, "file", fileUuid); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } + + @RequestMapping( + value = {"file/{fileType}/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String fileType, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + + try { + if (user == null) { + response.sendError(406, "User not logged in."); + return; + } + + BaseFile file = this.findFile(response, fileUuid, fileType, true, user.getSiteUuid()); + if (file == null || file.hasFileUrl()) { + return; + } + + String filePath = this.fileService.getFilePath(user.getSiteUuid(), fileType, fileUuid); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } catch (IOException var10) { + } + + } + + @RequestMapping( + value = {"file/report/template/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getReportTemplate(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String fileName) { + String filePath = this.reportService.getTemplateFilePath(fileName); + McFile file = new McFile(filePath); + if (!file.exists()) { + file = this.fileService.getResourceFile("report/" + fileName, false); + } + + McResource.copyFileToResponse(this.servletContext, response, file, fileName, 0, -1); + } + + @RequestMapping( + value = {"must/reserved/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getMustReservedFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String filePath = this.fileService.getMustDownloadFilePath(user.getSiteUuid(), fileUuid, "region"); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } + + @RequestMapping( + value = {"must/download/{isDirectory}/{fileUuid}/{fileName}/**"}, + method = {RequestMethod.GET} + ) + public void getMustDownloadFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName, @PathVariable String isDirectory) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + boolean isDir = Boolean.parseBoolean(isDirectory); + String path = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); + String[] tempPath = path.split("/", 7); + String filePath = this.fileService.getMustFolderFilePath(user.getSiteUuid(), fileUuid, tempPath[6]); + if (isDir) { + filePath = this.fileService.getMustDownloadProfilePath(user.getSiteUuid(), fileUuid, "tempDownlad", fileName); + fileName = fileName + ".zip"; + } + + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } + + @RequestMapping( + value = {"store/{fileType}/{packageName}/{versionCode}/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getStoreAppFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String fileType, @PathVariable String packageName, @PathVariable long versionCode, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String filePath = this.storeAppService.getStoreAppPath(packageName, versionCode, fileUuid); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } + + @RequestMapping( + value = {"store/ota/{productId}/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getStoreOtaFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String productId, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String filePath = this.storeOtaService.getStoreOtaFilePath(productId, fileUuid); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } + + @RequestMapping( + value = {"store/other/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getStoreOtherFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String filePath = this.storeOtherService.getStoreFilePath("other", fileUuid); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } + + @RequestMapping( + value = {"{siteUuid}/file/{fileType}/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String siteUuid, @PathVariable String fileType, @PathVariable String fileUuid, @PathVariable String fileName, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(name = "position",required = false,defaultValue = "0") Integer from) { + try { + BaseFile file = this.findFile(response, UUID.fromString(fileUuid), fileType, false, UUID.fromString(siteUuid)); + if (file == null || file.hasFileUrl()) { + return; + } + + String checksum = String.valueOf(file.getChecksum()); + if (etag != null && !etag.equals(checksum)) { + range = ""; + } + + String filePath = this.fileService.getFilePath(siteUuid, fileType, fileUuid); + Integer to = -1; + if (!Strings.isNullOrEmpty(range)) { + range = range.substring(range.indexOf(61) + 1); + if (range.indexOf(44) >= 0) { + response.sendError(400, "Multiple ranges not supported."); + return; + } + + boolean isRangeOk = true; + if (range.indexOf(45) >= 0) { + String[] tokens = range.split("-"); + if (tokens.length > 0) { + if (Strings.isNullOrEmpty(tokens[0])) { + to = (int)file.getLength() - 1; + from = to - Integer.valueOf(tokens[1]) + 1; + } else { + from = Integer.valueOf(tokens[0]); + if (tokens.length > 1) { + if (Strings.isNullOrEmpty(tokens[1])) { + to = (int)file.getLength() - 1; + } else { + to = Integer.valueOf(tokens[1]); + } + } else { + to = (int)file.getLength() - 1; + } + } + } else { + isRangeOk = false; + } + } + + if (!isRangeOk) { + response.sendError(400, "Range is invalid."); + return; + } + } + + response.addHeader("ETag", checksum); + response.addHeader("If-Match", checksum); + response.setDateHeader("Last-Modified", file.getLastModified()); + response.addHeader("Accept-Ranges", "bytes"); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, from, to); + } catch (Exception var17) { + } + + } + + @RequestMapping( + value = {"icon/app/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getAppIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + if (this.cloudStorageService.hasCloudStorage()) { + AppFile file = this.fileService.findApp(fileUuid, true); + if (file.hasIconUrl()) { + try { + String url = file.getIconUrl(); + response.sendRedirect(url); + return; + } catch (IOException var11) { + } + } + + String url = this.cloudStorageService.getUrl(user.getSiteUuid(), "app", fileUuid + ".png"); + if (!Strings.isNullOrEmpty(url)) { + try { + file.setIconUrl(url); + response.sendRedirect(url); + return; + } catch (IOException var10) { + } + } + } else { + String apkPath = this.fileService.getFilePath(user.getSiteUuid(), "app", fileUuid); + McFile iconFile = new McFile(apkPath + ".png"); + if (iconFile.exists()) { + byte[] iconData = iconFile.toBytes(); + if (iconData != null) { + String var10000 = Files.getNameWithoutExtension(fileName); + fileName = var10000 + (iconData[0] == 60 ? ".svg" : ".png"); + fileName = McUrlUtils.encode(fileName); + McResource.copyFileToResponse(this.servletContext, response, iconData, fileName); + return; + } + } + } + + this.getMimeIcon(request, response, authentication, "apk"); + } + } + + @RequestMapping( + value = {"icon/must/app/{profileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getMustSiteAppIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID profileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String iconFilePath = this.fileService.getMustFolderFilePath(user.getSiteUuid(), profileUuid, "apps/" + fileName + ".png"); + McFile iconFile = new McFile(iconFilePath); + if (!iconFile.exists()) { + } + + byte[] iconData = iconFile.toBytes(); + if (iconData != null) { + McResource.copyFileToResponse(this.servletContext, response, iconData, fileName + ".png"); + } else { + this.getMimeIcon(request, response, authentication, "apk"); + } + + } + } + + @RequestMapping( + value = {"icon/store/app/{packageName}"}, + method = {RequestMethod.GET} + ) + public void getStoreAppIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String packageName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String iconFilePath = this.storeAppService.getStoreIconPath(packageName); + McFile iconFile = new McFile(iconFilePath); + byte[] iconData = iconFile.toBytes(); + if (iconData != null) { + McResource.copyFileToResponse(this.servletContext, response, iconData, packageName + ".png"); + } else { + this.getMimeIcon(request, response, authentication, "apk"); + } + + } + } + + @RequestMapping( + value = {"icon/mime/{extension}"}, + method = {RequestMethod.GET} + ) + public void getMimeIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String extension) { + String resourcePath = Joiner.on('/').join("/image/mime", extension.toLowerCase() + ".png", new Object[0]); + if (!this.fileService.resourceExists(resourcePath, true)) { + resourcePath = "/image/mime/_blank.png"; + } + + forwardRequest(request, response, resourcePath); + } + + @RequestMapping( + value = {"icon/folder/{folderType}"}, + method = {RequestMethod.GET} + ) + public void getFolderIcon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String folderType) { + String resourcePath = Joiner.on('/').join("/image/folder", folderType.toLowerCase() + ".png", new Object[0]); + if (!this.fileService.resourceExists(resourcePath, true)) { + resourcePath = "/image/folder/normal.png"; + } + + forwardRequest(request, response, resourcePath); + } + + @RequestMapping( + value = {"profile/user/{userUuid}"}, + method = {RequestMethod.GET} + ) + public void getUserProfileImage(HttpServletRequest request, HttpServletResponse response, Authentication aHttputhentication, @PathVariable UUID userUuid) { + response.setHeader("Cache-Control", "max-age=2592000"); + String profilePath = this.fileService.getUserProfilePath(userUuid); + String fileName = "profile.jpg"; + if ((new File(profilePath)).exists()) { + McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "profile.jpg", 0, -1); + } else { + forwardRequest(request, response, "/image/icon/profileUnknown.png"); + } + + } + + @RequestMapping( + value = {"favicon"}, + method = {RequestMethod.GET} + ) + public void getFavicon(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestParam(required = false) UUID siteUuid) { + McFile favicon = new McFile(this.fileService.getFaviconPath()); + if (favicon.exists()) { + response.setHeader("Cache-Control", "max-age=2592000"); + McResource.copyFileToResponse(this.servletContext, response, favicon, favicon.getName(), 0, -1); + } else { + forwardRequest(request, response, "/image/favicon.png"); + } + + } + + @RequestMapping( + value = {"background"}, + method = {RequestMethod.GET} + ) + public void getBackgroundImage(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestParam(required = false) UUID siteUuid) { + if (siteUuid != null) { + String profilePath = this.fileService.getSiteFilePath(siteUuid, "background"); + String fileName = "background.jpg"; + McFile file = new McFile(profilePath); + if (file.exists()) { + response.setHeader("Cache-Control", "max-age=2592000"); + McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "background.jpg", 0, -1); + } else { + forwardRequest(request, response, "/image/bg/background.jpg"); + } + } else { + McFile bgFile = new McFile(this.fileService.getBackgroundPath()); + if (bgFile.exists()) { + response.setHeader("Cache-Control", "max-age=2592000"); + McResource.copyFileToResponse(this.servletContext, response, bgFile, bgFile.getName(), 0, -1); + } else { + forwardRequest(request, response, "/image/bg/background.jpg"); + } + } + + } + + @RequestMapping( + value = {"background/{siteUuid}"}, + method = {RequestMethod.GET} + ) + public void getSitebackgroundImage(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID siteUuid) { + this.getSiteImage(request, response, siteUuid, "background"); + } + + @RequestMapping( + value = {"logo/{siteUuid}"}, + method = {RequestMethod.GET} + ) + public void getSiteLogoImage(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID siteUuid) { + this.getSiteImage(request, response, siteUuid, "logo"); + } + + @RequestMapping( + value = {"profile/site/{siteUuid}"}, + method = {RequestMethod.GET} + ) + public void getSiteProfileImage(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID siteUuid) { + this.getSiteImage(request, response, siteUuid, "profile"); + } + + public void getSiteImage(HttpServletRequest request, HttpServletResponse response, UUID siteUuid, String type) { + if (this.cloudStorageService.hasCloudStorage()) { + String url = this.cloudStorageService.getUrl(siteUuid, type); + if (!Strings.isNullOrEmpty(url)) { + try { + response.sendRedirect(url); + return; + } catch (Exception var10) { + } + } + } + + McFile imgFile = new McFile(this.fileService.getSiteFilePath(siteUuid, type)); + String fileName = ""; + switch (type) { + case "background": + fileName = "backgroud.jpg"; + break; + case "logo": + fileName = "logo.png"; + break; + case "profile": + fileName = "profile.png"; + } + + if (imgFile.exists()) { + McResource.copyFileToResponse(this.servletContext, response, imgFile, fileName, 0, -1); + } else if (type.equals("background")) { + this.getBackgroundImage(request, response, (Authentication)null, (UUID)null); + } else if (type.equals("profile")) { + forwardRequest(request, response, "/image/icon/siteUnknown.png"); + } else { + try { + response.sendError(404, "Not found."); + } catch (IOException var9) { + } + } + + } + + @RequestMapping( + value = {"profile/org/{userUuid}"}, + method = {RequestMethod.GET} + ) + public void getOrgProfileImage(HttpServletResponse response, Authentication authentication, @PathVariable UUID userUuid) { + String profilePath = this.fileService.getFilePath("user", userUuid); + String fileName = "profile.jpg"; + McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "profile.jpg", 0, -1); + } + + @RequestMapping( + value = {"device/screen/{deviceUuid}"}, + method = {RequestMethod.GET} + ) + public void getDeviceScreenImage(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable UUID deviceUuid) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String profilePath = this.fileService.getDeviceFilePath(user.getSiteUuid(), deviceUuid, "screen", "screen.png"); + if (McFile.exists(profilePath)) { + McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "screen.png", 0, -1); + } else { + forwardRequest(request, response, "/image/empty.png"); + } + + } + } + + @RequestMapping( + value = {"device/file/{deviceUuid}/{hostFile}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getDeviceFile(HttpServletResponse response, Authentication authentication, @PathVariable UUID deviceUuid, @PathVariable String hostFile, @PathVariable String fileName) { + try { + Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid); + User user = UserPrincipal.getUser(authentication); + if (device != null && user != null && user.isBelongedToSite(device.getSiteUuid())) { + String filePath = this.fileService.getDeviceFilePath(device.getSiteUuid(), deviceUuid, "file", hostFile); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } else { + response.sendError(401, "Not logged in or Unauthorized."); + } + } catch (IOException var9) { + } + + } + + @RequestMapping( + value = {"file/checksum/{fileUuid}"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String getCheckSum(Authentication authentication, @PathVariable UUID fileUuid, @RequestParam(required = false) Integer size) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return null; + } else { + String path = this.fileService.getFilePath(user.getSiteUuid(), "other", fileUuid); + McFile file = new McFile(path); + Long checksum = file.getCrcChecksum(size); + return "" + checksum; + } + } + + public static void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path) { + try { + if (!response.isCommitted()) { + request.getRequestDispatcher(path).forward(request, response); + } + } catch (IOException | ServletException var6) { + try { + response.sendError(404); + } catch (IOException var5) { + } + } + + } + + private BaseFile findFile(HttpServletResponse response, UUID fileUuid, String fileType, boolean minify, UUID siteUuid) { + BaseFile file = null; + switch (fileType) { + case "app": + file = this.fileService.findApp(fileUuid, minify); + break; + case "ota": + file = this.fileService.findOta(fileUuid); + break; + case "other": + file = this.fileService.findFile(fileUuid); + break; + case "report": + file = this.reportService.findReportByUuid(fileUuid); + } + + try { + if (file == null) { + response.sendError(404); + } else if (file.hasFileUrl()) { + response.sendRedirect(file.getFileUrl()); + } else if (this.cloudStorageService.hasCloudStorage()) { + String url = this.cloudStorageService.getUrl(siteUuid, fileType, fileUuid); + if (!Strings.isNullOrEmpty(url)) { + file.setCloudUrl(url); + response.sendRedirect(url); + } + } + } catch (Exception var9) { + } + + return file; + } +} diff --git a/src/main/java/com/midm/controller/lib/ResourceController.java b/src/main/java/com/midm/controller/lib/ResourceController.java new file mode 100644 index 0000000..bd90720 --- /dev/null +++ b/src/main/java/com/midm/controller/lib/ResourceController.java @@ -0,0 +1,81 @@ +package com.midm.controller.lib; + +import com.google.common.base.Strings; +import com.google.common.io.Files; +import com.midm.controller.BaseController; +import com.mitac.cell.internet.http.McResponse; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class ResourceController extends BaseController { + @RequestMapping( + value = {"/js/**", "/css/**"}, + method = {RequestMethod.GET} + ) + public String getScript(HttpServletRequest request, Authentication authentication) { + return this.getResource(authentication, request.getServletPath()); + } + + @RequestMapping( + value = {"js/controller/login.js"}, + method = {RequestMethod.GET}, + produces = {"application/javascript"} + ) + public String getLoginScript(HttpServletRequest request, Model model, Authentication authentication, @RequestHeader("host") String hostHeader, @RequestParam(required = false) String hostParam, @RequestParam(required = false,defaultValue = "login") String pageFor) { + model.addAttribute("hasUser", this.userService.hasUser()); + model.addAttribute("pageFor", pageFor); + return this.getResource(authentication, request.getServletPath()); + } + + @RequestMapping( + value = {"/js/controller/resetPassword.js"}, + method = {RequestMethod.GET}, + produces = {"application/javascript"} + ) + public String getResetPasswordScript(HttpServletRequest request, Model model, Authentication authentication, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) UUID tokenUuid) { + model.addAttribute("error", userUuid == null); + model.addAttribute("tokenUuid", tokenUuid); + model.addAttribute("userUuid", userUuid); + return this.getResource(authentication, request.getServletPath()); + } + + @RequestMapping( + value = {"img/**"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public ResponseEntity getImage(HttpServletRequest request, Authentication authentication) { + String path = this.getTemplateResource(authentication, request.getServletPath()); + return this.getServletResource(request, path); + } + + @RequestMapping( + value = {"images/**"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public ResponseEntity getImages(HttpServletRequest request, Authentication authentication) { + String path = this.getTemplateResource(authentication, "/img" + request.getServletPath()); + return this.getServletResource(request, path); + } + + private ResponseEntity getServletResource(HttpServletRequest request, String path) { + String subType = Files.getFileExtension(path); + if (Strings.isNullOrEmpty(subType)) { + subType = "jpg"; + } + + return McResponse.getServletResource(request, new MediaType("image", subType), path); + } +} diff --git a/src/main/java/com/midm/controller/lib/StoreController.java b/src/main/java/com/midm/controller/lib/StoreController.java new file mode 100644 index 0000000..f61654e --- /dev/null +++ b/src/main/java/com/midm/controller/lib/StoreController.java @@ -0,0 +1,320 @@ +package com.midm.controller.lib; + +import com.google.common.base.Strings; +import com.midm.model.store.AppReleaseNote; +import com.midm.model.store.KeyStore; +import com.midm.model.store.StoreApp; +import com.midm.model.store.StoreAppFile; +import com.midm.model.store.StoreOtaFile; +import com.midm.model.store.StoreOtherFile; +import com.midm.model.store.StoreWebApp; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.file.FileService; +import com.midm.service.store.KeyStoreService; +import com.midm.service.store.StoreAppService; +import com.midm.service.store.StoreOtaService; +import com.midm.service.store.StoreOtherService; +import com.midm.service.store.StoreWebAppService; +import com.midm.service.system.HostLicenseService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.io.McResource; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.WebContext; + +@Controller +@RequestMapping({"store"}) +public class StoreController { + @Autowired + private ServletContext servletContext; + @Autowired + private StoreAppService storeAppService; + @Autowired + private StoreOtaService storeOtaService; + @Autowired + private StoreWebAppService storeWebAppService; + @Autowired + @Qualifier("stringTemplateEngine") + private TemplateEngine stringTemplateEngine; + @Autowired + private KeyStoreService keyStoreService; + @Autowired + private StoreOtherService storeOtherService; + @Autowired + private FileService fileService; + @Autowired + private CloudStorageService cloudStorageService; + @Autowired + @Lazy + private HostLicenseService hostLicenseService; + + @RequestMapping( + value = {"apps/download/{packageName}"}, + method = {RequestMethod.GET} + ) + public void getLatestApp(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(name = "checksum",required = false) String certMd5, @RequestParam(name = "keyStore",required = false) String keyStoreId, @RequestParam(required = false,defaultValue = "-1") int versionCode) { + if (Strings.isNullOrEmpty(certMd5) && !Strings.isNullOrEmpty(keyStoreId)) { + if (keyStoreId.equals("default")) { + keyStoreId = "android_default"; + } + + KeyStore keyStore = this.keyStoreService.find(keyStoreId); + certMd5 = keyStore.getCertMd5(); + } + + this.getApp(request, response, range, etag, packageName, String.valueOf(versionCode), keyStoreId, -1); + } + + @RequestMapping( + value = {"apps/{packageName}/{version}/{keyStoreId}"}, + method = {RequestMethod.GET} + ) + public void getApp(HttpServletRequest request, HttpServletResponse response, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @PathVariable String packageName, @PathVariable String version, @PathVariable String keyStoreId, @RequestParam(required = false,defaultValue = "-1") int sdkVersion) { + if (Strings.isNullOrEmpty(keyStoreId) || keyStoreId.equals("default")) { + keyStoreId = "android_default"; + } + + KeyStore keyStore = this.keyStoreService.find(keyStoreId); + if (keyStore == null) { + try { + response.sendError(404, "No key store exists."); + } catch (IOException var14) { + } + + } else { + String certMd5 = keyStore.getCertMd5(); + StoreAppFile appFile = null; + if (version.equalsIgnoreCase("latest")) { + appFile = this.storeAppService.findLatestAppFile(packageName, -1, sdkVersion, certMd5); + } else { + try { + long versionCode = Long.parseLong(version); + appFile = this.storeAppService.findAppFile(packageName, versionCode, certMd5); + } catch (Exception var16) { + } + } + + if (appFile != null) { + this.getApp(response, appFile, range); + } else { + try { + response.sendError(404, "No apps found."); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + } + + @RequestMapping( + value = {"app/{fileUuid}"}, + method = {RequestMethod.GET} + ) + public void getApp(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID fileUuid, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) { + StoreAppFile appFile = this.storeAppService.findAppFile(fileUuid); + if (appFile == null) { + try { + response.sendError(404, "App file not exists."); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + this.getApp(response, appFile, range); + } + + } + + private void getApp(HttpServletResponse response, StoreAppFile appFile, String range) { + String url = this.cloudStorageService.getUrl("store", "app", appFile.getPackageName(), appFile.getVersionCode(), appFile.getFileUuid()); + if (Strings.isNullOrEmpty(url)) { + String filePath = this.storeAppService.getStoreAppPath(appFile.getPackageName(), appFile.getVersionCode(), appFile.getFileUuid()); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), appFile.getFileName(), appFile.getLastModified(), range, appFile.getChecksum()); + } else { + try { + response.sendRedirect(url); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + + @RequestMapping( + value = {"apps/{packageName}/releaseNote"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String appReleaseNote(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @RequestParam(required = false,defaultValue = "-1") int sdkVersion) throws IOException { + return this.appReleaseNote(request, response, packageName, (String)null, (Integer)null, sdkVersion, true); + } + + @RequestMapping( + value = {"apps/{packageName}/{keyStore}/releaseNote", "apps/{packageName}/{keyStore}/releaseNote/{pathSdkVersion}"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String appReleaseNote(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @PathVariable String keyStore, @PathVariable(required = false) Integer pathSdkVersion, @RequestParam(required = false,defaultValue = "-1") int sdkVersion, @RequestParam(required = false,defaultValue = "1") Boolean isFormal) throws IOException { + WebContext context = new WebContext(request, response, this.servletContext, request.getLocale()); + StoreApp app = this.storeAppService.find(packageName); + if (pathSdkVersion != null) { + sdkVersion = pathSdkVersion; + } + + List notes = this.storeAppService.findReleaseNotes(packageName, sdkVersion, isFormal == null ? null : true); + context.setVariable("app", app); + context.setVariable("fixedKeyStores", Arrays.asList("mio", "default")); + if (!Strings.isNullOrEmpty(keyStore)) { + context.setVariable("keyStore", keyStore); + } + + context.setVariable("notes", notes); + List sdkVersions = this.storeAppService.getSdkVersions(packageName); + List sdkVersionsStr = (List)sdkVersions.stream().map(String::valueOf).collect(Collectors.toList()); + sdkVersionsStr.add(0, "All"); + context.setVariable("sdkVersions", sdkVersionsStr); + context.setVariable("selectedSdk", String.valueOf(sdkVersion)); + String helpTemplate = this.fileService.getResourceToString("help/app.releaseNote.html", false); + String result = this.stringTemplateEngine.process(helpTemplate, context); + return result; + } + + @RequestMapping( + value = {"apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink", "apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink/{pathSdkVersion}"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String appReleaseNoteShowAll(HttpServletRequest request, HttpServletResponse response, @PathVariable String packageName, @PathVariable String keyStore, @PathVariable(required = false) Integer pathSdkVersion, @RequestParam(required = false,defaultValue = "-1") int sdkVersion) throws IOException { + return this.appReleaseNote(request, response, packageName, keyStore, pathSdkVersion, sdkVersion, (Boolean)null); + } + + @RequestMapping( + value = {"ota/{fileUuid}"}, + method = {RequestMethod.GET} + ) + public void getOta(HttpServletRequest request, HttpServletResponse response, @PathVariable UUID fileUuid, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) { + StoreOtaFile otaFile = this.storeOtaService.findOtaFile(fileUuid); + + try { + if (otaFile == null) { + response.sendError(404, "System update file not exists."); + } else { + String url = this.cloudStorageService.getUrl("store", "ota", otaFile.getProductId(), fileUuid); + if (Strings.isNullOrEmpty(url)) { + String filePath = this.storeOtaService.getStoreOtaFilePath(otaFile.getProductId(), fileUuid); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), otaFile.getFileName(), otaFile.getLastModified(), range, otaFile.getChecksum()); + } else { + response.sendRedirect(url); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + @RequestMapping( + value = {"webapp/{fileUuid}"}, + method = {RequestMethod.GET} + ) + public void getWebApp(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileUuid, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) throws IOException { + StoreWebApp app = null; + + try { + app = this.storeWebAppService.find(UUID.fromString(fileUuid)); + } catch (Exception var10) { + app = this.storeWebAppService.find((String)null, (String)null, fileUuid); + } + + this.getWebApp(response, app, range); + } + + @RequestMapping( + value = {"webapp/latest"}, + method = {RequestMethod.GET} + ) + public void getWebApp(HttpServletRequest request, HttpServletResponse response, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false,defaultValue = "com.mitac") String groupId, @RequestParam(required = false,defaultValue = "midm") String artifactId, @RequestParam(required = false,defaultValue = "true") boolean isFormal) throws IOException { + StoreWebApp app = this.storeWebAppService.findLatest(groupId, artifactId, isFormal); + this.getWebApp(response, app, range); + } + + private void getWebApp(HttpServletResponse response, StoreWebApp app, String range) { + try { + if (app != null) { + String url = this.cloudStorageService.getUrl("store", "webapp", app.getFileUuid()); + if (Strings.isNullOrEmpty(url)) { + String filePath = this.storeWebAppService.getStoreFilePath(app.getFileUuid()); + McFile file = new McFile(filePath); + if (file.exists()) { + McResource.copyFileToResponse(this.servletContext, response, file, app.getFileName(), app.getLastModified(), range, app.getChecksum()); + } else { + response.sendError(404, "Webapp file not exists."); + } + } else { + response.sendRedirect(url); + } + } else { + response.sendError(404, "Webapp file not exists."); + } + } catch (IOException var7) { + } + + } + + @RequestMapping( + value = {"webapp/releaseNote"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String webAppReleaseNote(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false,defaultValue = "com.mitac") String groupId, @RequestParam(required = false,defaultValue = "midm") String artifactId, @RequestParam(required = false) String version, @RequestParam(required = false,defaultValue = "0") int limit, @RequestParam(required = false,defaultValue = "true") boolean isFormal) throws IOException { + List webapp = this.storeWebAppService.findAll(groupId, artifactId, version, limit); + WebContext context = new WebContext(request, response, this.servletContext, request.getLocale()); + context.setVariable("title", "MiDM Host Release Note"); + context.setVariable("apps", webapp); + context.setVariable("isFormal", isFormal); + String helpTemplate = this.fileService.getResourceToString("help/webapp.releaseNote.html", false); + String result = this.stringTemplateEngine.process(helpTemplate, context); + return result; + } + + @RequestMapping( + value = {"other/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getOtherFile(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName, @RequestHeader(name = "range",required = false) String range, @RequestHeader(name = "if-match",required = false) String etag, @RequestParam(required = false) Long position, @RequestParam(required = false) Long checksum) { + StoreOtherFile file = this.storeOtherService.findByUuidOrNameOrAlias(fileName); + + try { + if (file == null) { + response.sendError(404, "System update file not exists."); + } else { + String url = this.cloudStorageService.getUrl("store", "other", file.getFileUuid()); + if (Strings.isNullOrEmpty(url)) { + String filePath = this.storeOtherService.getStoreFilePath("other", file.getFileUuid()); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), file.getFileName(), file.getLastModified(), range, file.getChecksum()); + } else { + response.sendRedirect(url); + } + } + } catch (IOException var11) { + } + + } +} diff --git a/src/main/java/com/midm/dpc/DpcController.java b/src/main/java/com/midm/dpc/DpcController.java new file mode 100644 index 0000000..9a12849 --- /dev/null +++ b/src/main/java/com/midm/dpc/DpcController.java @@ -0,0 +1,161 @@ +package com.midm.dpc; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.SiteInfo; +import com.midm.model.org.User; +import com.midm.model.store.StoreAppFile; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.store.StoreAppService; +import com.mitac.cell.barcode.QrCode; +import com.mitac.cell.io.McResource; +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.web.util.UriComponentsBuilder; + +/** + * ====================================================================================== + * Android Enterprise 设备策略控制器配置与零接触二维码生成器 (DpcController) + * ====================================================================================== + * + *

【Android Enterprise / 谷歌企业移动管理 (EMM) 规范实现】 + * 1. 业务场景(零接触配置与开箱即用 - Zero-Touch Enrollment): + * - 当企业采购批量的全新 Android 手持终端/平板开机时,在开机欢迎界面连续点击 6 次, + * 系统将自动唤起系统级摄像头扫描器; + * - 扫描由本控制器 {@link #qrCode} 生成的特制二维码,即可实现无人工干预的静默绑定。 + * 2. 【DPC 配置规范 (Provisioning Bundle)】: + * - 动态组装包含应用下载地址、SHA-256 校验哈希(Checksum)、 + * DeviceAdminReceiver 组件名称及企业 Wi-Fi 预置参数的 JSON 捆绑包; + * - 设备扫描后,Android 操作系统会自动静默下载 DPC 客户端并将其提权激活为设备所有者(Device Owner), + * 获得最高系统级管控权限(如锁屏禁用、静默安装、Kiosk单应用专机模式)。 + * + * @author MiDM Core Platform Team + */ +@Controller +public class DpcController { + @Autowired + private StoreAppService storeAppService; + @Autowired + private UserService userService; + @Autowired + private SiteService siteService; + + /** + * 生成供 Android 设备开箱扫描的 DPC 零接触配置二维码图片流 + * + * @param request HTTP 请求 + * @param response HTTP 响应(直接输出 PNG 图像二进制流) + * @param size 图像尺寸大小 + * @param margin 图像白边边距 + * @param dpc DPC 参数载荷模型 + */ + @RequestMapping( + value = {"/dpc/qr"}, + method = {RequestMethod.GET} + ) + public void qrCode(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Integer size, @RequestParam(required = false) Integer margin, DpcModel dpc) { + this.toDpcConfig(request, dpc); + McResource.copyToResponse(response, QrCode.toImage(dpc.toDpcConfig(), size, margin)); + } + + /** + * 获取 JSON 格式的 DPC 原生配置文本(供批量打单或定制初始化应用提取) + */ + @RequestMapping( + value = {"/dpc/config"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String intent(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Integer size, @RequestParam(required = false) Integer margin, DpcModel dpc) { + return this.toDpcConfig(request, dpc); + } + + private String toDpcConfig(HttpServletRequest request, DpcModel dpc) { + String adminPackage = dpc.getDeviceAdmin(); + if (!Strings.isNullOrEmpty(adminPackage) && adminPackage.indexOf(47) < 0) { + if (adminPackage.equals("com.mitac.midm.dpc")) { + dpc.setDeviceAdmin(Joiner.on("").join(adminPackage, "/", new Object[]{adminPackage, ".MidmDeviceAdminReceiver"})); + StoreAppFile appFile = this.storeAppService.findLatestAppFile(adminPackage, -1, -1, (String)null); + if (appFile != null) { + String filePath = this.storeAppService.getStoreAppPath(adminPackage, appFile.getVersionCode(), appFile.getFileUuid()); + dpc.setPackageChecksum(DpcUtils.getChecksum(new File(filePath))); + } + + String downloadUrl = dpc.getDownloadUrl(); + if (Strings.isNullOrEmpty(downloadUrl)) { + UriComponentsBuilder builder = ServletUriComponentsBuilder.fromRequestUri(request).replacePath(Joiner.on("").join(request.getContextPath(), "/store/apps/download/", new Object[]{adminPackage})); + if (builder.build().getHost().endsWith("mic.com.tw")) { + builder.scheme("https"); + } + + downloadUrl = builder.build().toUriString(); + dpc.setDownloadUrl(downloadUrl); + } + } else if (adminPackage.equals("com.mitac.must.service")) { + dpc.setDeviceAdmin(Joiner.on("").join(adminPackage, "/", new Object[]{adminPackage, ".MustDeviceAdminReceiver"})); + } else if (adminPackage.equals("com.mitac.midm.system")) { + dpc.setDeviceAdmin(Joiner.on("").join(adminPackage, "/", new Object[]{adminPackage, ".MidmDeviceAdminReceiver"})); + } + } + + if (!Strings.isNullOrEmpty(dpc.getDownloadUrl()) && Strings.isNullOrEmpty(dpc.getPackageChecksum())) { + try { + URL url = new URL(dpc.getDownloadUrl()); + dpc.setPackageChecksum(DpcUtils.getChecksum(url)); + } catch (MalformedURLException var13) { + } + } + + DpcModel.MidmConfig midmConfig = dpc.getMidm(); + if (midmConfig != null) { + String email = midmConfig.getEmail(); + String password = midmConfig.getPassword(); + String siteModel = midmConfig.getSiteId(); + if (!Strings.isNullOrEmpty(siteModel) && !Strings.isNullOrEmpty(email) && !Strings.isNullOrEmpty(password)) { + User user = this.userService.findUserByEmail(email); + if (user != null && this.userService.matchPassword(user, password)) { + for(SiteInfo siteInfo : user.getSites()) { + UUID siteUuid = siteInfo.getSiteUuid(); + Site site = this.siteService.findByUuid(siteUuid); + if (site != null && siteModel.equals(site.getModel())) { + midmConfig.setSiteId(siteUuid.toString()); + midmConfig.setEmail((String)null); + midmConfig.setPassword((String)null); + break; + } + } + } + } + } + + return dpc.toDpcConfig(); + } + + @RequestMapping( + value = {"/dpc/checksum"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String getChecksum(HttpServletRequest request, HttpServletResponse response, @RequestParam String url) { + try { + String checksum = DpcUtils.getChecksum(new URL(url)); + return MidmResponse.getSucceedResponse((Object)checksum); + } catch (MalformedURLException var5) { + return MidmResponse.getFailedResponse(); + } + } +} diff --git a/src/main/java/com/midm/dpc/DpcModel.java b/src/main/java/com/midm/dpc/DpcModel.java new file mode 100644 index 0000000..e32de03 --- /dev/null +++ b/src/main/java/com/midm/dpc/DpcModel.java @@ -0,0 +1,280 @@ +package com.midm.dpc; + +import com.google.common.base.Strings; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.SerializedName; +import org.springframework.security.crypto.password.PasswordEncoder; + +public class DpcModel { + public static final String COMPONENT_MUST_SERVICE = "com.mitac.must.service/com.mitac.must.service.MustDeviceAdminReceiver"; + public static final String COMPONENT_MIDM_DPC = "com.mitac.midm.dpc/com.mitac.midm.dpc.MidmDeviceAdminReceiver"; + @SerializedName( + value = "android.app.extra.PROVISIONING_WIFI_SSID", + alternate = {"ssid"} + ) + private String ssid; + @SerializedName( + value = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE", + alternate = {"security"} + ) + private String security; + @SerializedName( + value = "android.app.extra.PROVISIONING_WIFI_PASSWORD", + alternate = {"password"} + ) + private String password; + @SerializedName( + value = "android.app.extra.PROVISIONING_WIFI_HIDDEN", + alternate = {"hidden"} + ) + private Boolean hidden; + @SerializedName( + value = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED", + alternate = {"enableAllSystemApps"} + ) + private boolean enableAllSystemApps = true; + @SerializedName( + value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME", + alternate = {"deviceAdmin"} + ) + private String deviceAdmin; + @SerializedName( + value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM", + alternate = {"packageChecksum"} + ) + private String packageChecksum; + @SerializedName( + value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION", + alternate = {"downloadUrl"} + ) + private String downloadUrl; + @SerializedName( + value = "android.app.extra.PROVISIONING_LOCALE", + alternate = {"locale"} + ) + private String locale; + @SerializedName( + value = "android.app.extra.PROVISIONING_TIME_ZONE", + alternate = {"timeZone"} + ) + private String timeZone; + @SerializedName( + value = "android.app.extra.PROVISIONING_LOCAL_TIME", + alternate = {"localTime"} + ) + private String localTime; + @SerializedName( + value = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE", + alternate = {"midm"} + ) + private MidmConfig midmConfig; + + public String getSsid() { + return this.ssid; + } + + public void setSsid(String ssid) { + this.ssid = ssid; + } + + public String getSecurity() { + return this.security; + } + + public void setSecurity(String securityType) { + this.security = securityType; + } + + public String getPassword() { + return this.password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void encryptPassword(PasswordEncoder passwordEncoder) { + if (this.midmConfig != null && !Strings.isNullOrEmpty(this.midmConfig.getPassword())) { + this.midmConfig.setPassword(passwordEncoder.encode(this.midmConfig.getPassword())); + } + + } + + public boolean hidden() { + return this.hidden; + } + + public void setHidden(boolean isHidden) { + this.hidden = isHidden; + } + + public boolean isEnableAllSystemApps() { + return this.enableAllSystemApps; + } + + public void setEnableAllSystemApps(boolean enableAllSystemApps) { + this.enableAllSystemApps = enableAllSystemApps; + } + + public String getDeviceAdmin() { + return this.deviceAdmin; + } + + public void setDeviceAdmin(String deviceAdmin) { + this.deviceAdmin = deviceAdmin; + } + + public String getDeviceAdminPackageName() { + if (Strings.isNullOrEmpty(this.deviceAdmin)) { + return null; + } else { + int indexSlash = this.deviceAdmin.indexOf(47); + return indexSlash < 0 ? this.deviceAdmin : this.deviceAdmin.substring(0, this.deviceAdmin.indexOf(47)); + } + } + + public String getPackageChecksum() { + return this.packageChecksum; + } + + public void setPackageChecksum(String packageChecksum) { + this.packageChecksum = packageChecksum; + } + + public String getDownloadUrl() { + return this.downloadUrl; + } + + public void setDownloadUrl(String downloadUrl) { + this.downloadUrl = downloadUrl; + } + + public String getLocale() { + return this.locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } + + public MidmConfig getMidm() { + return this.midmConfig; + } + + public void setMidm(MidmConfig midm) { + this.midmConfig = midm; + } + + public String toDpcConfig() { + Gson gson = (new GsonBuilder()).disableHtmlEscaping().create(); + return gson.toJson(this); + } + + public static class MidmConfig { + @SerializedName( + value = "midm.host.url", + alternate = {"hostUrl"} + ) + private String hostUrl; + @SerializedName( + value = "midm.app.client.url", + alternate = {"clientAppUrl"} + ) + private String clientAppUrl; + @SerializedName( + value = "midm.app.system.url", + alternate = {"systemAppUrl"} + ) + private String systemAppUrl; + @SerializedName( + value = "midm.app.install.latest", + alternate = {"updateLatest"} + ) + private Boolean updateLatest; + @SerializedName( + value = "midm.app.install.slient", + alternate = {"installSilent"} + ) + private Boolean installSilent; + @SerializedName( + value = "midm.site", + alternate = {"siteId"} + ) + private String siteId; + @SerializedName( + value = "midm.email", + alternate = {"email"} + ) + private String email; + @SerializedName( + value = "midm.password", + alternate = {"password"} + ) + private String password; + + public String getHostUrl() { + return this.hostUrl; + } + + public void setHostUrl(String url) { + this.hostUrl = url; + } + + public String getClientAppUrl() { + return this.clientAppUrl; + } + + public void setClientAppUrl(String clientAppUrl) { + this.clientAppUrl = clientAppUrl; + } + + public String getSystemAppUrl() { + return this.systemAppUrl; + } + + public void setSystemAppUrl(String systemAppUrl) { + this.systemAppUrl = systemAppUrl; + } + + public Boolean getUpdateLatest() { + return this.updateLatest; + } + + public void setUpdateLatest(Boolean updateLatest) { + this.updateLatest = updateLatest; + } + + public Boolean getInstallSilent() { + return this.installSilent; + } + + public void setInstallSilent(Boolean installSilent) { + this.installSilent = installSilent; + } + + public String getSiteId() { + return this.siteId; + } + + public void setSiteId(String siteId) { + this.siteId = siteId; + } + + public String getEmail() { + return this.email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return this.password; + } + + public void setPassword(String password) { + this.password = password; + } + } +} diff --git a/src/main/java/com/midm/dpc/DpcUtils.java b/src/main/java/com/midm/dpc/DpcUtils.java new file mode 100644 index 0000000..83f551a --- /dev/null +++ b/src/main/java/com/midm/dpc/DpcUtils.java @@ -0,0 +1,36 @@ +package com.midm.dpc; + +import com.mitac.cell.io.McFile; +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import org.apache.commons.io.IOUtils; + +public class DpcUtils { + public static String getChecksum(URL url) { + try { + return getChecksum(IOUtils.toByteArray(url.openStream())); + } catch (IOException var2) { + return null; + } + } + + public static String getChecksum(File file) { + return !file.exists() ? null : getChecksum((new McFile(file)).toBytes()); + } + + public static String getChecksum(byte[] bytes) { + try { + MessageDigest shaDigest = MessageDigest.getInstance("SHA-256"); + byte[] hash = shaDigest.digest(bytes); + String checksum = Base64.getEncoder().withoutPadding().encodeToString(hash); + checksum = checksum.replaceAll("[+]", "-").replaceAll("/", "_"); + return checksum; + } catch (NoSuchAlgorithmException var4) { + return null; + } + } +} diff --git a/src/main/java/com/midm/model/GeneralProfile.java b/src/main/java/com/midm/model/GeneralProfile.java new file mode 100644 index 0000000..3658536 --- /dev/null +++ b/src/main/java/com/midm/model/GeneralProfile.java @@ -0,0 +1,241 @@ +package com.midm.model; + +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McBooleanUtils; +import com.mitac.cell.utils.McDateTimeUtils; +import java.util.Date; +import java.util.UUID; +import org.bson.Document; +import org.joda.time.DateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.Indexed; + +public class GeneralProfile { + @Id + protected UUID uuid; + protected DbObject profile; + protected DbObject settings; + protected Date created; + @Indexed + protected Date updated; + protected Boolean enabled; + + public void init() { + this.generateId(); + this.created = new Date(); + this.updated = this.created; + } + + public void generateId() { + this.uuid = UUID.randomUUID(); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public DbObject getProfile() { + if (this.profile == null) { + this.profile = new DbObject(); + } + + return this.profile; + } + + public void setProfile(DbObject profile) { + this.profile = profile; + } + + public DbObject getSettings() { + if (this.settings == null) { + this.settings = new DbObject(); + } + + return this.settings; + } + + public void setSettings(DbObject settings) { + this.settings = settings; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getUpdated() { + return this.updated; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } + + public void setUpdated() { + this.setUpdated(new Date()); + } + + public boolean getEnabled() { + return this.enabled != null && this.enabled; + } + + public boolean isEnded() { + if ("ends".equals(this.getProfile("endsOption"))) { + DateTime dateTime = McDateTimeUtils.parseDate((String)this.getProfile("ends"), "yyyy-MM-dd").plusDays(1); + return dateTime.isBeforeNow(); + } else { + return false; + } + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Object getProfile(String key) { + return this.getProfile(key, (Object)null); + } + + public Object getProfile(String key, Object defaultValue) { + if (this.getProfile().containsKey(key)) { + try { + return this.getProfile().get(key); + } catch (Exception var4) { + } + } + + return defaultValue; + } + + public boolean getProfileAsBoolean(String category, String key, String subCategory, String item, boolean def) { + Boolean value = McBooleanUtils.isTrue(this.getProfile(category, key, subCategory, item)); + return value == null ? def : value; + } + + public Object getProfile(String category, String key, String subCategory, String item) { + return this.getProfileCategory(category, key, subCategory).get(item); + } + + public DbObject getProfileCategory(String... categoryNames) { + return this.getProfile().getDbObject(categoryNames); + } + + public Object getCategoryProfile(String category, String key) { + return this.getProfileCategory(category) == null ? null : this.getProfileCategory(category).get(key); + } + + public void setProfile(String key, Object value) { + this.getProfile().put(key, value); + } + + public void setProfile(String category, String key, Object value) { + this.getProfileCategory(category).put(key, value); + } + + public void setProfile(String category, String subCategory, String item, String key, Object value) { + this.getProfileCategory(category, subCategory, item).put(key, value); + } + + public void removeProfile(String key) { + if (this.profile != null) { + this.profile.remove(key); + } + + } + + public Object getSetting(String key) { + return this.getSettings().get(key); + } + + public String getSettingAsString(String key) { + return this.getSettings().getString(key, (String)null); + } + + public int getSettingAsInt(String key, int def) { + return this.getSettings().getInteger(key, def); + } + + public float getSettingAsFloat(String key, float def) { + return this.getSettings().getFloat(key, def); + } + + public boolean getSettingAsBoolean(String key) { + return this.getSettingAsBoolean(key, false); + } + + public boolean getSettingAsBoolean(String key, boolean def) { + return this.getSettings().containsKey(key) ? McBooleanUtils.isTrue(this.getSetting(key)) : def; + } + + public boolean getSettingAsBoolean(String category, String key, boolean def) { + Boolean value = McBooleanUtils.isTrue(this.getSetting(category, key)); + return value == null ? def : value; + } + + public UUID getSettingAsUuid(String key) { + return this.getSettings().getUuid(key); + } + + public DbObject getSettingsCategory(String... categoryNames) { + return this.getSettings().getDbObject(categoryNames); + } + + public Object getSetting(String category, String key) { + return this.getSettingsCategory(category).get(key); + } + + public void setSetting(String key, UUID value) { + if (value != null) { + this.getSettings().put(key, value.toString()); + } else { + this.getSettings().remove(key); + } + + } + + public void setSetting(String key, Object value) { + this.getSettings().put(key, value); + } + + public void setSetting(String categoryName, String key, Object value) { + Document dbObject = this.getSettingsCategory(categoryName); + if (value != null) { + dbObject.put(key, value); + } else { + dbObject.remove(key); + } + + } + + public void removeOption(String key) { + this.getSettings().remove(key); + } + + public String getName() { + Object value = this.getProfile("name"); + return value == null ? null : (String)value; + } + + public void setName(String name) { + this.setProfile("name", name); + } + + public String getDescription() { + return (String)this.getProfile("desc"); + } + + public void setDescription(String desc) { + this.setProfile("desc", desc); + } + + public void minify() { + this.created = null; + } +} diff --git a/src/main/java/com/midm/model/GroupByResult.java b/src/main/java/com/midm/model/GroupByResult.java new file mode 100644 index 0000000..c6793cb --- /dev/null +++ b/src/main/java/com/midm/model/GroupByResult.java @@ -0,0 +1,26 @@ +package com.midm.model; + +public class GroupByResult { + private String[] groups; + private int count; + + public int getCount() { + return this.count; + } + + public void setCount(int count) { + this.count = count; + } + + public String getGroup() { + return this.groups.length > 0 ? this.groups[0] : null; + } + + public String[] getGroups() { + return this.groups; + } + + public void setGroups(String[] groups) { + this.groups = groups; + } +} diff --git a/src/main/java/com/midm/model/IF_EXISTS_OPTION.java b/src/main/java/com/midm/model/IF_EXISTS_OPTION.java new file mode 100644 index 0000000..28b68ce --- /dev/null +++ b/src/main/java/com/midm/model/IF_EXISTS_OPTION.java @@ -0,0 +1,31 @@ +package com.midm.model; + +import com.google.common.base.CharMatcher; + +public enum IF_EXISTS_OPTION { + ignore(0), + skip(0), + replace(1), + overwrite(1), + update(2), + modify(2), + remove(3); + + public int option; + + private IF_EXISTS_OPTION(int option) { + this.option = option; + } + + public static IF_EXISTS_OPTION get(String key) { + try { + return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); + } catch (Exception var2) { + return skip; + } + } + + public static int getOption(String option) { + return get(option).option; + } +} diff --git a/src/main/java/com/midm/model/battery/Battery.java b/src/main/java/com/midm/model/battery/Battery.java new file mode 100644 index 0000000..0b4c1c5 --- /dev/null +++ b/src/main/java/com/midm/model/battery/Battery.java @@ -0,0 +1,126 @@ +package com.midm.model.battery; + +import com.google.gson.reflect.TypeToken; +import com.midm.model.GeneralProfile; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McJsonUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.CompoundIndexes; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@CompoundIndexes({@CompoundIndex( + def = "{'profile.hardware_info.batterySerial':1}", + unique = true +)}) +public class Battery extends GeneralProfile { + private UUID siteUuid; + private DbObject states; + @Transient + private String deviceGroupPath; + + public Battery() { + this.init(); + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public String getBatterySerial() { + return (String)this.getCategoryProfile("hardware_info", "batterySerial"); + } + + public String getDeviceSerial() { + return (String)this.getCategoryProfile("hardware_info", "deviceSerial"); + } + + public void setDeviceSerial(String deviceSerial) { + this.setProfile("hardware_info", "deviceSerial", deviceSerial.trim()); + } + + public String getModel() { + return (String)this.getCategoryProfile("hardware_info", "model"); + } + + public String getDeviceId() { + return (String)this.getCategoryProfile("hardware_info", "device_id"); + } + + public void setRegisterState(String state) { + this.getStates().put("state", state); + } + + public String getRegisterState() { + return this.getStates().getString("state"); + } + + public Integer getBatteryCondition() { + return this.getStates().getInteger("batteryCondition", -1); + } + + public DbObject getStates() { + if (this.states == null) { + this.states = new DbObject(); + } + + return this.states; + } + + public String getDeviceGroupPath() { + return this.deviceGroupPath; + } + + public void setDeviceGroupPath(String deviceGroupPath) { + this.deviceGroupPath = deviceGroupPath; + } + + public ValueWithTime getLastTemp() { + List dbTempList = (List)McJsonUtils.toObject(McJsonUtils.toJson(this.getStates().get("temperature")), (new TypeToken() { + }).getType()); + return dbTempList.isEmpty() ? null : (ValueWithTime)dbTempList.get(0); + } + + public void setLastTemp(ValueWithTime t) { + DbObject obj = new DbObject(); + obj.append("reportedAt", t.getReportedAt()).append("value", t.getValue()); + List list = new ArrayList(); + list.add(obj); + this.getStates().put("temperature", list); + } + + public static enum BATTERY_CONDITION { + UNKNOWN(-1), + GOOD(0), + AVERAGE(1), + SERVICE_SOON(2); + + private int value; + + private BATTERY_CONDITION(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public static BATTERY_CONDITION forValue(int value) { + for(BATTERY_CONDITION e : values()) { + if (e.value == value) { + return e; + } + } + + return UNKNOWN; + } + } +} diff --git a/src/main/java/com/midm/model/battery/BatteryLog.java b/src/main/java/com/midm/model/battery/BatteryLog.java new file mode 100644 index 0000000..3902fb6 --- /dev/null +++ b/src/main/java/com/midm/model/battery/BatteryLog.java @@ -0,0 +1,51 @@ +package com.midm.model.battery; + +import com.mitac.cell.db.DbObject; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@CompoundIndex( + def = "{batterySerial: 1, reportedAt: 1}" +) +public class BatteryLog { + @Id + private UUID uuid = UUID.randomUUID(); + @Indexed + private String batterySerial; + @Indexed + private String category; + private String log; + @Indexed + private Date reportedAt; + private DbObject states; + private Date recordedAt = new Date(); + + public UUID getUuid() { + return this.uuid; + } + + public String getBatterySerial() { + return this.batterySerial; + } + + public void setCategory(String category) { + this.category = category; + } + + public DbObject getStates() { + if (this.states == null) { + this.states = new DbObject(); + } + + return this.states; + } + + public Date getReportedAt() { + return this.reportedAt; + } +} diff --git a/src/main/java/com/midm/model/battery/ValueWithTime.java b/src/main/java/com/midm/model/battery/ValueWithTime.java new file mode 100644 index 0000000..43ed85e --- /dev/null +++ b/src/main/java/com/midm/model/battery/ValueWithTime.java @@ -0,0 +1,29 @@ +package com.midm.model.battery; + +import java.util.Date; + +public class ValueWithTime { + private Date reportedAt; + private double value; + + public ValueWithTime(Date reportedAt, double value) { + this.reportedAt = reportedAt; + this.value = value; + } + + public Date getReportedAt() { + return this.reportedAt; + } + + public void setReportedAt(Date reportedAt) { + this.reportedAt = reportedAt; + } + + public double getValue() { + return this.value; + } + + public void setValue(double value) { + this.value = value; + } +} diff --git a/src/main/java/com/midm/model/device/AppInfo.java b/src/main/java/com/midm/model/device/AppInfo.java new file mode 100644 index 0000000..92a83f6 --- /dev/null +++ b/src/main/java/com/midm/model/device/AppInfo.java @@ -0,0 +1,91 @@ +package com.midm.model.device; + +import com.google.common.base.Strings; + +public class AppInfo { + private String packageName; + private String label; + private String versionName; + private Integer versionCode; + private Integer minSdkVersion; + private Long appSize; + private Long dataSize; + private Long firstInstalled; + private Long lastUpdated; + + public String getPackageName() { + return this.packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getLabel() { + return Strings.isNullOrEmpty(this.label) ? this.packageName : this.label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getVersionName() { + return this.versionName; + } + + public void setVersionName(String versionName) { + this.versionName = versionName; + } + + public int getVersionCode() { + return this.versionCode; + } + + public void setVersionCode(int versionCode) { + this.versionCode = versionCode; + } + + public int minSdkVersion() { + return this.minSdkVersion; + } + + public void setMinSdkVersion(int version) { + this.minSdkVersion = version; + } + + public long getAppSize() { + return this.appSize; + } + + public void setAppSize(long appSize) { + this.appSize = appSize; + } + + public long getDataSize() { + return this.dataSize; + } + + public void setDataSize(long dataSize) { + this.dataSize = dataSize; + } + + public long getFirstInstalled() { + return this.firstInstalled; + } + + public void setFirstInstalled(long firstInstalled) { + this.firstInstalled = firstInstalled; + } + + public long getLastUpdated() { + return this.lastUpdated; + } + + public void setLastUpdated(long lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public String toString() { + return String.format("%s %s(%s)", this.label, this.versionName, this.packageName); + } +} diff --git a/src/main/java/com/midm/model/device/DEVICE_PROPERTY.java b/src/main/java/com/midm/model/device/DEVICE_PROPERTY.java new file mode 100644 index 0000000..b8ad864 --- /dev/null +++ b/src/main/java/com/midm/model/device/DEVICE_PROPERTY.java @@ -0,0 +1,51 @@ +package com.midm.model.device; + +import com.google.common.base.CharMatcher; + +public enum DEVICE_PROPERTY { + serialno, + serial_no, + serialnumber, + serial_number, + productsn, + product_sn, + partno, + partnumber, + part_no, + palletno, + pallet_no, + cartonsn, + carton_sn, + wifimac, + wifi_mac, + device_group, + devicegroup, + group, + owner, + owner_name, + owner_email, + owner_phone, + owner_mobile, + email, + description, + desc, + comment, + memo, + exists, + ifexists, + if_exists, + license, + renew, + renewtosamemodel, + renew_to_same_model, + rsa, + unknown; + + public static DEVICE_PROPERTY get(String key) { + try { + return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); + } catch (Exception var2) { + return unknown; + } + } +} diff --git a/src/main/java/com/midm/model/device/DataUsage.java b/src/main/java/com/midm/model/device/DataUsage.java new file mode 100644 index 0000000..b09fe90 --- /dev/null +++ b/src/main/java/com/midm/model/device/DataUsage.java @@ -0,0 +1,137 @@ +package com.midm.model.device; + +import com.mitac.cell.db.DbObject; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@CompoundIndex( + def = "{deviceUuid: 1, siteUuid: 1}" +) +public class DataUsage { + @Id + private UUID uuid; + private UUID deviceUuid; + private UUID siteUuid; + @Indexed + private Date from; + @Indexed + private Date to; + private DbObject usage; + @Indexed( + expireAfterSeconds = 15552000 + ) + private Date recordedAt; + + public DataUsage() { + this.uuid = UUID.randomUUID(); + this.recordedAt = new Date(); + } + + public DataUsage(Device device, DbObject report) { + this(); + this.setSiteUuid(device.getSiteUuid()); + this.setDeviceUuid(device.getUuid()); + this.usage = report; + DbObject wifiProperty = report.getDbObject(new String[]{"wifi"}); + DbObject mobileProperty = report.getDbObject(new String[]{"mobile"}); + long from = mobileProperty.getLong("from", wifiProperty.getLong("from")); + this.from = new Date(from); + long to = mobileProperty.getLong("to", wifiProperty.getLong("to")); + this.to = new Date(to); + if (wifiProperty.isEmpty()) { + report.remove("wifi"); + } else if (wifiProperty.getLong("tx", 0L) + wifiProperty.getLong("rx", 0L) == 0L) { + report.remove("wifi"); + } else { + wifiProperty.remove("from"); + wifiProperty.remove("to"); + } + + if (mobileProperty.isEmpty()) { + report.remove("mobile"); + } else if (mobileProperty.getLong("tx", 0L) + mobileProperty.getLong("rx", 0L) == 0L) { + report.remove("mobile"); + } else { + mobileProperty.remove("from"); + mobileProperty.remove("to"); + } + + if (this.usage.isEmpty()) { + this.usage = null; + } + + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public UUID getDeviceUuid() { + return this.deviceUuid; + } + + public void setDeviceUuid(UUID deviceUuid) { + this.deviceUuid = deviceUuid; + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public Date getFrom() { + return this.from; + } + + public void setFrom(Date from) { + this.from = from; + } + + public Date getTo() { + return this.to; + } + + public void setTo(Date to) { + this.to = to; + } + + public DbObject getUsage() { + return this.usage; + } + + public long getUsage(String category, String key) { + return this.getUsage().getDbObject(new String[]{category}).getLong(key, 0L); + } + + public void setUsage(DbObject usage) { + this.usage = usage; + } + + public Date getRecordedAt() { + return this.recordedAt; + } + + public void setRecordedAt(Date recordedAt) { + this.recordedAt = recordedAt; + } + + public boolean isLaterThan(DataUsage usage) { + return usage.getTo().getTime() < this.getFrom().getTime(); + } + + public boolean isOverlapped(DataUsage usage) { + return usage.getFrom().getTime() >= this.getTo().getTime() && usage.getTo().getTime() <= this.getTo().getTime(); + } +} diff --git a/src/main/java/com/midm/model/device/Device.java b/src/main/java/com/midm/model/device/Device.java new file mode 100644 index 0000000..20c57d1 --- /dev/null +++ b/src/main/java/com/midm/model/device/Device.java @@ -0,0 +1,495 @@ +package com.midm.model.device; + +import com.google.common.base.Strings; +import com.midm.model.GeneralProfile; +import com.midm.model.battery.Battery; +import com.midm.model.file.OtaFile; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McJsonUtils; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import org.bson.Document; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.CompoundIndexes; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.DBRef; + +/** + * ====================================================================================== + * 核心实体模型:受控终端设备档案 (Device Entity) + * ====================================================================================== + * + *

【数据建模与 MongoDB 索引架构】 + * 1. 业务地位: + * - 作为整个 MDM / IoT 系统的核心资产抽象,代表一台具体的受控智能硬件(PDA / 移动平板 / 车载终端)。 + * 2. 【生产级复合索引设计】: + * - `{'profile.hardware_info.serial_no': 1}` (unique = true): + * 以出厂序列号构建唯一业务主键索引,杜绝重复设备接入,提供 O(1) 复杂度的极速检索。 + * - `{'deviceGroup.$id': 1}`: + * 按部门/仓库/车辆编队等组织分组高效检索关联设备。 + * - `{'owner.$id': 1, 'deviceGroup.$id': 1}`: + * 加速管理员按员工责任人与所属部门进行组合过滤统计。 + * 3. 关联映射({@link DBRef}): + * - 关联所属企业员工 (User owner)、商业授权凭据 (DeviceLicense license)、组织分组 (DeviceGroup deviceGroup)。 + * 4. 动态属性集(DbObject): + * - `profile`:静态硬件特征(IMEI、MAC、CPU型号、屏幕分辨率、出厂镜像版本); + * - `states`:动态运行快照(当前电量、实时网络类型、内存剩余空间、活跃IP); + * - `installedApps`:端侧已安装的应用清单快照(用于合规检测与版本审计)。 + * + * @author MiDM Core Platform Team + */ +@org.springframework.data.mongodb.core.mapping.Document +@CompoundIndexes({@CompoundIndex( + def = "{'deviceGroup.$id':1}" +), @CompoundIndex( + def = "{'profile.hardware_info.serial_no':1}", + unique = true +), @CompoundIndex( + def = "{'owner.$id':1, 'deviceGroup.$id':1}" +)}) +public class Device extends GeneralProfile { + /** 所属企业租户主键 UUID(实现多租户严格逻辑隔离) */ + private UUID siteUuid; + + /** 临时字段:前端传递的目标分组 UUID,不持久化到 MongoDB */ + @Transient + private UUID groupUuid; + + /** 临时字段:展示给前端的分组全路径(如 "总公司/华东大区/智能物流一号仓") */ + @Transient + private String groupPath; + + /** 临时字段:归属负责人主键 UUID */ + @Transient + private UUID ownerUuid; + + /** MongoDB 跨集合引用:设备领用人档案 */ + @DBRef + private User owner; + + /** MongoDB 跨集合引用:设备绑定的商业 License 授权凭据 */ + @DBRef + private DeviceLicense license; + + /** MongoDB 跨集合引用:所属层级组织分组 */ + @DBRef + private DeviceGroup deviceGroup; + + /** 临时字段:设备当前生效的策略清单缓存 */ + @Transient + private List deviceProfiles; + + /** 许可激活时间点索引 */ + @Indexed + private Date licensed; + + /** 许可到期时间点索引(用于定时扫描批量过期告警与自动续约) */ + @Indexed + private Date licenseExpiry; + + /** 临时字段:RSA 鉴权私钥字符串 */ + @Transient + private String rsa; + + /** 终端动态遥测快照数据字典(电池状态、网络、存储剩余空间等) */ + protected DbObject states; + + /** 首次入网注册时间戳 */ + private Date enrolled; + + /** 最近一次活跃心跳上报时间(Check-in,用于离线判定) */ + private Date lastCheckedIn; + + /** 最近一次 TCP / WebSocket 连接断开时间点 */ + private Date lastDisconnected; + + /** 终端已安装的应用程序包信息清单快照 */ + private List installedApps; + + public String getRsa() { + return this.rsa; + } + + public void setRsa(String rsa) { + this.rsa = rsa; + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public UUID getGroupUuid() { + return this.groupUuid; + } + + public String getGroupPath() { + return this.groupPath; + } + + public void setGroupPath(String groupPath) { + this.groupPath = groupPath; + } + + public User getOwner() { + return this.owner; + } + + public void setOwner(User owner) { + this.owner = owner; + if (owner != null) { + this.removeProfile("owner"); + } + + } + + public UUID getOwnerUuid() { + return this.ownerUuid; + } + + public void setOwnerUuid(UUID ownerUuid) { + this.ownerUuid = ownerUuid; + } + + public boolean hasOwner() { + return this.getOwner() != null; + } + + public String getOwnerInfo(String key, String defaultValue) { + if (this.owner == null) { + DbObject owner = this.getProfileCategory(new String[]{"owner"}); + return (String)owner.get(key, defaultValue); + } else { + return key.equals("email") ? this.owner.getEmail() : (String)this.owner.getProfile(key, defaultValue); + } + } + + public boolean isAssociated() { + return this.getDeviceGroup() != null; + } + + public boolean canRegister() { + return !Strings.isNullOrEmpty(this.getSerialNo()); + } + + public DeviceGroup getDeviceGroup() { + return this.deviceGroup; + } + + public void setDeviceGroup(DeviceGroup deviceGroup) { + if (deviceGroup != null && deviceGroup.getSiteUuid().equals(this.getSiteUuid())) { + this.deviceGroup = deviceGroup; + } else { + this.groupUuid = null; + this.deviceGroup = null; + } + + } + + public DbObject getStates() { + if (this.states == null) { + this.states = new DbObject(); + } + + return this.states; + } + + public void setStates(DbObject states) { + this.states = states; + } + + public String getState() { + return this.getStates().getString("state", "unknown"); + } + + public void setState(String state) { + this.setState("state", state); + } + + public boolean isOnline() { + return this.getStates().getBoolean("isOnline", false); + } + + public void setOnline(boolean online) { + this.setState("isOnline", online); + } + + public boolean isBlocked() { + return this.getStates().containsKey("blocked"); + } + + public void setState(String key, Object value) { + this.getStates().append(key, value); + } + + public void setClientVersion(int version) { + this.getStates().put("clientVersion", version); + } + + public int getClientVersion() { + return this.getStates().getInteger("clientVersion", -1); + } + + public Battery.BATTERY_CONDITION getBatteryCondition() { + return Battery.BATTERY_CONDITION.forValue(this.getStates().getInteger("batteryCondition", -1)); + } + + public boolean hasOldClient() { + return this.getClientVersion() < 0; + } + + public Date getEnrolled() { + return this.enrolled; + } + + public boolean isEnrolled() { + return this.enrolled != null; + } + + public void setEnrolled(Date enrolled) { + this.enrolled = enrolled; + this.setState("enrolled"); + this.setLicenseExpiry(); + } + + public boolean isRetired() { + return this.getState().equals("retired"); + } + + public Date getLastCheckedIn() { + return this.lastCheckedIn; + } + + public void setLastCheckedIn() { + this.setLastCheckedIn(new Date()); + } + + public void setLastCheckedIn(Date lastCheckedIn) { + this.lastCheckedIn = lastCheckedIn; + } + + public Date getLastDisconnected() { + return this.lastDisconnected; + } + + public void setLastDisconnected() { + this.lastDisconnected = new Date(); + } + + public void setLastDisconnected(Date disconnected) { + this.lastDisconnected = disconnected; + } + + public List getInstalledApps() { + return this.installedApps; + } + + public void setInstalledApps(List installedApps) { + this.installedApps = installedApps; + } + + public void setDeviceProfiles(List deviceProfiles) { + this.deviceProfiles = deviceProfiles; + } + + public String getSerialNo() { + return (String)this.getCategoryProfile("hardware_info", "serial_no"); + } + + public void setSerialNo(String serialNo) { + this.setProfile("hardware_info", "serial_no", serialNo.trim()); + } + + public String getModelId() { + return (String)this.getCategoryProfile("hardware_info", "product_id"); + } + + public String getBuildNo() { + return this.getProfileCategory(new String[]{"software_info"}).getString("build_no"); + } + + public String getDisplayId() { + return this.getProfileCategory(new String[]{"software_info"}).getString("display_id"); + } + + public String getProductDisplayId() { + return this.getProfileCategory(new String[]{"software_info"}).getString("product_display_id"); + } + + public long getBuildDate() { + return this.getProfileCategory(new String[]{"software_info"}).getLong("build_date", -1L); + } + + public int getSdkVersion() { + if (this.isEnrolled()) { + int version = this.getProfileCategory(new String[]{"software_info"}).getInteger("sdk_version", -1); + if (version < 0) { + String osVersion = this.getProfileCategory(new String[]{"software_info"}).getString("os_version"); + if (!Strings.isNullOrEmpty(osVersion)) { + if (osVersion.startsWith("5.")) { + version = 22; + } else if (osVersion.startsWith("6.")) { + version = 23; + } else if (osVersion.startsWith("7.")) { + version = 25; + } else if (osVersion.startsWith("8.")) { + version = 27; + } else if (osVersion.equals("9")) { + version = 28; + } + } + } + + return version; + } else { + return -1; + } + } + + public String getCustomerId() { + return (String)this.getCategoryProfile("software_info", "customer_id"); + } + + public String getRegionImgVersion() { + return this.getProfile().getDbObject(new String[]{"software_info"}).getString("region_version"); + } + + public String getScriptVersion() { + return (String)this.getCategoryProfile("software_info", "script_version"); + } + + public long getRegionBuildDate() { + return this.getProfile().getDbObject(new String[]{"software_info"}).getLong("region_build_date"); + } + + public boolean isGmsAvailable() { + return this.getProfile().getDbObject(new String[]{"software_info"}).getBoolean("gms_available"); + } + + public String getSkuId() { + String skuId = (String)this.getCategoryProfile("hardware_info", "sku_id"); + if (skuId == null) { + if (this.isGmsAvailable()) { + String buildNo = this.getBuildNo(); + if (buildNo == null) { + buildNo = this.getDisplayId(); + } + + if (buildNo != null) { + skuId = buildNo.substring(0, buildNo.indexOf(".")); + } + } else { + skuId = OtaFile.parseSkuId(this.getDisplayId()); + } + + if (skuId == null) { + skuId = OtaFile.parseSkuId(this.getProductDisplayId()); + } + + if (skuId == null) { + skuId = OtaFile.parseSkuId(this.getBuildNo()); + } + + if (skuId != null) { + this.setProfile("hardware_info", "sku_id", skuId); + } + } + + return skuId; + } + + public String getDeviceId() { + return (String)this.getCategoryProfile("hardware_info", "device_id"); + } + + public String getBuildFingerPrint() { + return (String)this.getCategoryProfile("software_info", "build_fingerprint"); + } + + public boolean isMobileConnected() { + String type = this.getProfileCategory(new String[]{"network", "active"}).getString("type"); + return "MOBILE".equalsIgnoreCase(type); + } + + public String getWifiMacAddr() { + return this.getProfileCategory(new String[]{"network", "wifi"}).getString("mac_address"); + } + + public DeviceLicense getLicense() { + return this.license; + } + + public void setLicense(DeviceLicense license) { + this.license = license; + if (license != null) { + this.licensed = new Date(); + this.setLicenseExpiry(); + } + + } + + public Date getLicensed() { + return this.licensed; + } + + public void setLicensed(Date licensed) { + this.licensed = licensed; + } + + private void setLicenseExpiry() { + if (this.hasLicense()) { + if (!this.license.isActivated() && this.isEnrolled()) { + this.license.activate(); + } + + this.setLicenseExpiry(this.license.getExpiry()); + } + } + + public Date getLicenseExpiry() { + if (this.licenseExpiry == null && this.hasLicense()) { + this.licenseExpiry = this.license.getExpiry(); + } + + return this.licenseExpiry; + } + + public boolean isLicenseExpired() { + return this.license != null && !this.license.isPerpetual() && this.license.isExpired(); + } + + public void setLicenseExpiry(Date expiry) { + this.licenseExpiry = expiry; + } + + public boolean hasLicense() { + return this.license != null; + } + + public boolean isTrial() { + return !this.hasLicense() || this.license.isTrial(); + } + + public void removeLicense() { + this.setLicense((DeviceLicense)null); + } + + public String getPlan() { + return this.license.getPlan(); + } + + public void reset() { + this.setEnrolled((Date)null); + this.getStates().clear(); + } + + public Device clone() { + return (Device)McJsonUtils.clone(this); + } +} diff --git a/src/main/java/com/midm/model/device/DeviceApps.java b/src/main/java/com/midm/model/device/DeviceApps.java new file mode 100644 index 0000000..9b781a6 --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceApps.java @@ -0,0 +1,150 @@ +package com.midm.model.device; + +import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class DeviceApps { + @Id + private UUID deviceUuid; + @Transient + private String serialNo; + private String category = "installed"; + private List apps; + private Date reported = new Date(); + + public UUID getDeviceUuid() { + return this.deviceUuid; + } + + public void setDeviceUuid(UUID deviceUuid) { + this.deviceUuid = deviceUuid; + } + + public String getSerialNo() { + return this.serialNo; + } + + public void setSerialNo(String serialNo) { + this.serialNo = serialNo; + } + + public String getCategory() { + return this.category; + } + + public void setCategory(String category) { + this.category = category; + } + + public List getApps() { + return this.apps; + } + + public void setApps(List apps) { + this.apps = apps; + } + + public AppInfo getClientService() { + return this.getApp("com.mitac.midm.client"); + } + + public void setClientService(AppInfo appInfo) { + this.setApp(appInfo); + } + + public AppInfo getSystemService() { + return this.getApp("com.mitac.midm.system"); + } + + public void setSystemService(AppInfo appInfo) { + this.setApp(appInfo); + } + + public AppInfo getApp(String packageName) { + if (this.apps != null) { + for(AppInfo app : this.apps) { + String appPackage = app.getPackageName(); + if (packageName.equals(appPackage)) { + return app; + } + } + } + + return null; + } + + public void setApp(AppInfo newApp) { + if (newApp != null && !Strings.isNullOrEmpty(newApp.getPackageName())) { + if (this.apps == null) { + this.apps = new ArrayList(); + } + + this.apps.add(newApp); + } + } + + public void fixAbnormal() { + Iterator it = this.apps.iterator(); + + while(it.hasNext()) { + AppInfo info = (AppInfo)it.next(); + String packageName = info.getPackageName(); + String label = info.getLabel(); + if (Strings.isNullOrEmpty(packageName)) { + it.remove(); + } else if (Strings.isNullOrEmpty(label)) { + info.setLabel(packageName); + } + } + + } + + public Date getReported() { + return this.reported; + } + + public void setReported(Date reported) { + this.reported = reported; + } + + public boolean isAppInstalled(int deviceSdk, String packageName, long versionCode, int minSdk) { + if (minSdk != -1 && deviceSdk < minSdk) { + return true; + } else { + AppInfo appInfo = this.getApp(packageName); + return appInfo != null ? (long)appInfo.getVersionCode() >= versionCode : false; + } + } + + public boolean equals(Object obj) { + List newApps = null; + if (obj instanceof DeviceApps) { + DeviceApps deviceApps = (DeviceApps)obj; + newApps = deviceApps.getApps(); + if (this.apps != null && newApps != null && this.apps.size() == newApps.size()) { + if (this.apps.isEmpty()) { + return true; + } + + for(AppInfo newAppInfo : newApps) { + AppInfo curInfo = this.getApp(newAppInfo.getPackageName()); + if (curInfo == null || newAppInfo.getVersionCode() != curInfo.getVersionCode()) { + return false; + } + } + + return true; + } + } + + return false; + } +} diff --git a/src/main/java/com/midm/model/device/DeviceGroup.java b/src/main/java/com/midm/model/device/DeviceGroup.java new file mode 100644 index 0000000..05c57c3 --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceGroup.java @@ -0,0 +1,91 @@ +package com.midm.model.device; + +import com.midm.model.GeneralProfile; +import java.util.List; +import java.util.UUID; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class DeviceGroup extends GeneralProfile implements Comparable { + private UUID siteUuid; + private UUID parentUuid; + private Integer order; + @Transient + private Integer deviceNumbers; + private List children; + + public DeviceGroup() { + this.deviceNumbers = 0; + } + + public DeviceGroup(UUID uuid) { + this.uuid = uuid; + } + + public DeviceGroup(UUID siteUuid, UUID parentUuid, String name) { + this.init(); + this.siteUuid = siteUuid; + this.parentUuid = parentUuid; + this.setName(name); + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public UUID getParentUuid() { + return this.parentUuid; + } + + public void setParentUuid(UUID parentUuid) { + this.parentUuid = parentUuid; + } + + public Integer getOrder() { + return this.order; + } + + public void setOrder(Integer order) { + this.order = order; + } + + public Integer getDeviceNumbers() { + return this.deviceNumbers; + } + + public void setDeviceNumbers(Integer numbers) { + this.deviceNumbers = numbers == null ? 0 : numbers; + } + + public List getChildren() { + return this.children; + } + + public void setChildren(List children) { + this.children = children; + } + + public boolean equals(UUID uuid) { + return this.uuid != null && this.uuid.equals(uuid); + } + + public int compareTo(Object target) { + UUID targetUuid = null; + if (target instanceof UUID) { + targetUuid = (UUID)target; + } else if (target instanceof DeviceGroup) { + targetUuid = ((DeviceGroup)target).getUuid(); + } + + if (targetUuid == null) { + return this.uuid == null ? 0 : 1; + } else { + return this.uuid == null ? -1 : this.uuid.compareTo(targetUuid); + } + } +} diff --git a/src/main/java/com/midm/model/device/DeviceKey.java b/src/main/java/com/midm/model/device/DeviceKey.java new file mode 100644 index 0000000..9bf5d38 --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceKey.java @@ -0,0 +1,48 @@ +package com.midm.model.device; + +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class DeviceKey { + @Id + private UUID uuid; + @Indexed + private String deviceSerial; + private String rsa; + private Date created; + + public DeviceKey() { + this((String)null, (String)null); + } + + public DeviceKey(String deviceSerial, String rsa) { + this.uuid = UUID.randomUUID(); + this.created = new Date(); + this.deviceSerial = deviceSerial; + this.rsa = rsa; + } + + public String getDeviceSerial() { + return this.deviceSerial; + } + + public void setDeviceSerial(String deviceSerial) { + this.deviceSerial = deviceSerial; + } + + public String getRsa() { + return this.rsa; + } + + public void setRsa(String rsa) { + this.rsa = rsa; + } + + public Date getCreated() { + return this.created; + } +} diff --git a/src/main/java/com/midm/model/device/DeviceLicense.java b/src/main/java/com/midm/model/device/DeviceLicense.java new file mode 100644 index 0000000..0e903b4 --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceLicense.java @@ -0,0 +1,427 @@ +package com.midm.model.device; + +import com.midm.model.org.Site; +import com.midm.model.org.SiteLicense; +import com.midm.model.system.LicenseModel; +import com.mitac.cell.utils.McDateTimeUtils; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.CompoundIndexes; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@CompoundIndexes({@CompoundIndex( + def = "{'site.$id': 1}" +), @CompoundIndex( + def = "{'siteLicense.$id': 1}" +), @CompoundIndex( + def = "{'licenseModel.$id': 1}" +), @CompoundIndex( + def = "{'plan': 1, 'site.$id': 1, 'expiry': 1}" +), @CompoundIndex( + def = "{'plan': 1, 'licenseModel.$id': 1, 'site.$id': 1, 'expiry': 1}" +), @CompoundIndex( + def = "{'plan': 1, 'childSite.$id': 1, 'licenseModel.$id': 1, 'site.$id': 1, 'expiry': 1}" +), @CompoundIndex( + def = "{'plan': 1,\t'childSite.$id': 1, 'site.$id': 1, 'expiry': 1}" +), @CompoundIndex( + def = "{'childSite.$id': 1, 'site.$id': 1, 'expiry': 1}" +)}) +public class DeviceLicense { + @Id + private UUID uuid; + @Indexed + private UUID deviceUuid; + @Indexed + private String deviceSerial; + @DBRef + private SiteLicense siteLicense; + @DBRef + private SiteLicense childSiteLicense; + @DBRef + private Site site; + @DBRef + private Site childSite; + @DBRef + private LicenseModel licenseModel; + private String plan; + private boolean autoRenew; + private boolean renewToSameModel; + private int activationCount; + @Indexed + private Date activatedAt; + @Indexed + private Date expiry; + private List reactivated; + private Date created; + + public DeviceLicense() { + this.plan = "standard"; + this.autoRenew = false; + this.renewToSameModel = false; + this.uuid = UUID.randomUUID(); + this.created = new Date(); + } + + public DeviceLicense(SiteLicense license) { + this((Device)null, (SiteLicense)license); + } + + public DeviceLicense(SiteLicense license, String plan) { + this((Device)null, (SiteLicense)license); + this.setPlan(plan); + } + + public DeviceLicense(Device device) { + this(); + this.setDevice(device); + } + + public DeviceLicense(Device device, SiteLicense license) { + this(); + this.setSiteLicense(license); + this.setDevice(device); + } + + public DeviceLicense(Device device, LicenseModel licenseModel) { + this(); + this.setLicenseModel(licenseModel); + this.setDevice(device); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public SiteLicense getSiteLicense() { + return this.siteLicense; + } + + public void setSiteLicense(SiteLicense license) { + this.siteLicense = license; + if (license != null) { + this.setSite(license.getSite()); + this.setLicenseModel(license.getLicenseModel()); + } else { + this.setLicenseModel((LicenseModel)null); + } + + } + + public SiteLicense getChildSiteLicense() { + return this.childSiteLicense; + } + + public void setChildSiteLicense(SiteLicense license) { + this.childSiteLicense = license; + } + + public boolean isLite() { + return this.site.isLite() || this.plan.equals("lite"); + } + + public Site getSite() { + return this.site; + } + + public void setSite(Site site) { + if (site == null) { + this.site = this.childSite = null; + } else if (site.isChild()) { + this.setSite(site.getReseller()); + this.setChildSite(site); + } else { + this.site = site; + } + + } + + public Site getChildSite() { + return this.childSite; + } + + public void setChildSite(Site child) { + this.childSite = child; + } + + public boolean hasLicenseModel() { + return this.getLicenseModel() != null; + } + + public LicenseModel getLicenseModel() { + return this.licenseModel; + } + + public void setLicenseModel(LicenseModel licenseModel) { + this.setLicenseModel(licenseModel, true); + } + + public void setLicenseModel(LicenseModel licenseModel, boolean setExpiry) { + this.licenseModel = licenseModel; + if (licenseModel != null && setExpiry) { + this.expiry = this.licenseModel.getFreshExpiry(new Date()); + } + + } + + public UUID getDeviceUuid() { + return this.deviceUuid; + } + + public void setDeviceUuid(UUID deviceUuid) { + this.deviceUuid = deviceUuid; + } + + public boolean setDevice(Device device) { + if (this.isExceedActivationCount() && this.beforeExpiry()) { + return false; + } else if (device == null) { + if (this.isTrial()) { + this.expire(); + } else { + this.setDeviceUuid((UUID)null); + this.setDeviceSerial((String)null); + this.setAutoRenew(false); + this.setRenewToSameModel(false); + if (this.isExceedActivationCount()) { + this.expire(); + } + } + + return true; + } else { + this.setDeviceSerial(device.getSerialNo()); + this.setDeviceUuid(device.getUuid()); + if (device.isEnrolled()) { + if (this.isActivated()) { + ++this.activationCount; + if (this.isPerpetual()) { + Date nextExpiry = this.licenseModel.getNextExpiry(new Date()); + if (this.expiry.before(nextExpiry)) { + this.expiry = nextExpiry; + } + } + } else { + this.activate(); + } + } + + return true; + } + } + + public String getDeviceSerial() { + return this.deviceSerial; + } + + public void setDeviceSerial(String serialNo) { + this.deviceSerial = serialNo; + } + + public String getPlan() { + return this.plan; + } + + public void setPlan(String plan) { + this.plan = plan; + } + + public boolean isAutoRenew() { + return this.autoRenew; + } + + public void setAutoRenew(boolean autoRenew) { + this.autoRenew = autoRenew; + } + + public boolean isRenewToSameModel() { + return this.renewToSameModel; + } + + public void setRenewToSameModel(boolean renewToSameModel) { + this.renewToSameModel = renewToSameModel; + } + + public int getActivationCount() { + return this.activationCount; + } + + public void setActivationCount(int count) { + if (count < 0) { + count = 0; + } + + this.activationCount = count; + if (this.activationCount == 0) { + this.setActivatedAt((Date)null); + } + + } + + public void resetActivationCount() { + if (this.isTrial()) { + this.setActivationCount(0); + this.setActivatedAt((Date)null); + } else { + this.setActivationCount(--this.activationCount); + } + + } + + public boolean exceedActivationCount(int maxActivationCount) { + return this.activationCount > maxActivationCount; + } + + public boolean isActive() { + return this.activatedAt == null; + } + + public boolean isActivated() { + return this.activatedAt != null; + } + + public boolean isExpired() { + return !this.beforeExpiry(); + } + + public boolean canExtend() { + if (!this.isPerpetual()) { + return false; + } else { + List reactivated = this.getReactivated(); + if ((reactivated == null || reactivated.size() != 2) && (!this.isExceedActivationCount() || this.getDeviceUuid() != null)) { + DateTime expiry = new DateTime(this.getExpiry()); + DateTime now = DateTime.now(); + return now.plusDays(45).isAfter(expiry) && expiry.plusDays(14).isAfter(now); + } else { + return false; + } + } + } + + public Date getActivatedAt() { + return this.activatedAt; + } + + public Boolean activate() { + return this.isActivated() ? true : this.setActivatedAt(new Date()); + } + + public Boolean setActivatedAt(Date activatedAt) { + if (!this.isActivated()) { + this.activatedAt = activatedAt; + this.expiry = this.licenseModel.getActivatedExpiry(activatedAt); + if (activatedAt != null) { + ++this.activationCount; + } + + return true; + } else if (this.isActivated() && this.activationCount < this.licenseModel.getMaxActivation()) { + if (activatedAt != null) { + ++this.activationCount; + } + + return true; + } else { + return false; + } + } + + public void reset() { + this.setDevice((Device)null); + } + + public Date getExpiry() { + return this.expiry; + } + + public boolean beforeExpiry() { + return this.expiry != null && this.expiry.after(new Date()); + } + + public void setExpiry(Date expiryDate) { + this.expiry = expiryDate; + } + + public void extendExpiryDays(int days) { + this.setExpiry((new DateTime()).plusDays(days).toDate()); + } + + public void expire() { + this.setExpiry(new Date()); + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public boolean isPerpetual() { + return this.licenseModel != null && this.licenseModel.isPerpetual(); + } + + public boolean isTrial() { + return this.siteLicense == null || this.licenseModel == null || this.licenseModel.isTrial(); + } + + public boolean isExceedActivationCount() { + int maxCount = this.licenseModel == null ? 2 : this.licenseModel.getMaxActivation(); + return maxCount > 0 && maxCount <= this.activationCount; + } + + public boolean isValid() { + return this.isPerpetual() ? true : (new Date()).before(this.expiry); + } + + public boolean isSameLicenseModel(UUID licenseModelUuid) { + return this.licenseModel != null && this.licenseModel.getUuid().equals(licenseModelUuid); + } + + public int getRemainingDays() { + return this.expiry.before(new Date()) ? 0 : McDateTimeUtils.daysBetween(new DateTime(this.expiry), DateTime.now()); + } + + public List getReactivated() { + return this.reactivated; + } + + public void setReactivated(List reactivated) { + this.reactivated = reactivated; + } + + public boolean reactivate() { + if (this.isPerpetual()) { + if (this.reactivated == null) { + this.reactivated = new ArrayList(); + } + + if (this.reactivated.size() < 2) { + LocalDate today = LocalDate.now(); + this.reactivated.add(today.toDate()); + this.setExpiry((new DateTime(this.getExpiry())).plusYears(1).toDate()); + return true; + } + } + + return false; + } + + public String getPo() { + return this.childSiteLicense != null ? this.childSiteLicense.getPo() : (this.siteLicense != null ? this.siteLicense.getPo() : null); + } +} diff --git a/src/main/java/com/midm/model/device/DeviceNote.java b/src/main/java/com/midm/model/device/DeviceNote.java new file mode 100644 index 0000000..a242a95 --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceNote.java @@ -0,0 +1,73 @@ +package com.midm.model.device; + +import com.midm.model.org.User; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class DeviceNote { + @Id + private UUID uuid; + private UUID deviceUuid; + private UUID writerUuid; + @Transient + private User writer; + private String note; + private Date registeredAt; + + public void init() { + this.setUuid(UUID.randomUUID()); + this.setRegisteredAt(new Date()); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public UUID getDeviceUuid() { + return this.deviceUuid; + } + + public void setDeviceUuid(UUID deviceUuid) { + this.deviceUuid = deviceUuid; + } + + public UUID getWriterUuid() { + return this.writerUuid; + } + + public void setWriterUuid(UUID writerUuid) { + this.writerUuid = writerUuid; + } + + public User getWriter() { + return this.writer; + } + + public void setWriter(User writer) { + this.writer = writer; + } + + public String getNote() { + return this.note; + } + + public void setNote(String note) { + this.note = note; + } + + public Date getRegisteredAt() { + return this.registeredAt; + } + + public void setRegisteredAt(Date registeredAt) { + this.registeredAt = registeredAt; + } +} diff --git a/src/main/java/com/midm/model/device/DeviceProfile.java b/src/main/java/com/midm/model/device/DeviceProfile.java new file mode 100644 index 0000000..17c8571 --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceProfile.java @@ -0,0 +1,349 @@ +package com.midm.model.device; + +import com.google.gson.annotations.Expose; +import com.midm.model.GeneralProfile; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McJsonUtils; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@CompoundIndex( + def = "{'deviceProfileGroup.uuid': 1}" +) +public class DeviceProfile extends GeneralProfile { + @Indexed + private UUID siteUuid; + @DBRef + private DeviceProfileGroup deviceProfileGroup; + private UUID writerUuid; + private boolean isGlobal; + private DbObject status; + private ProfileApps apps; + private List otas; + private DbObject files; + private ProfileScope scope; + private List sequence; + @Transient + private DbObject progress; + @Transient + private DbObject reference; + @Transient + private UUID groupUuid; + @Transient + private User writer; + @Expose( + serialize = false + ) + @Transient + private boolean needOldFormat = false; + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public boolean isGlobal() { + return this.isGlobal; + } + + public void setIsGlobal(boolean isGlobal) { + this.isGlobal = isGlobal; + } + + public UUID getGroupUuid() { + return this.groupUuid; + } + + public void setGroupUuid(UUID groupUuid) { + this.groupUuid = groupUuid; + } + + public DeviceProfileGroup getDeviceProfileGroup() { + return this.deviceProfileGroup; + } + + public void setDeviceProfileGroup(DeviceProfileGroup deviceProfileGroup) { + this.deviceProfileGroup = deviceProfileGroup; + if (deviceProfileGroup == null) { + this.groupUuid = null; + } + + } + + public Set getFileUUids() { + Set pushUuids = new HashSet(); + if (this.files != null && !this.files.isEmpty() && this.files.containsKey("push")) { + List pushes = this.files.getList("push", DbObject.class); + pushes.forEach((pushItem) -> { + List sources = pushItem.getList("sources", Object.class); + sources.forEach((source) -> { + if (source instanceof UUID) { + pushUuids.add((UUID)source); + } else if (source instanceof String) { + pushUuids.add(UUID.fromString((String)source)); + } + + }); + }); + } + + return pushUuids; + } + + public String applyOrder() { + return this.getProfile().getString("applyOrder", "none"); + } + + public List getSequence() { + return this.sequence; + } + + public boolean hasSequence() { + return this.sequence != null && !this.sequence.isEmpty(); + } + + public void setSequence(List sequence) { + this.sequence = sequence; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public UUID getWriterUuid() { + return this.writerUuid; + } + + public void setWriterUuid(UUID writerUuid) { + this.writerUuid = writerUuid; + } + + public DbObject getStatus() { + return this.status; + } + + public void setStatus(DbObject status) { + this.status = status; + } + + public ProfileScope getScope() { + return this.scope; + } + + public boolean hasScope() { + return this.scope != null && this.scope.hasScoped(); + } + + public boolean hasScopeDeviceGroups() { + return this.scope != null && this.scope.getGroup() != null && !this.scope.getGroup().isEmpty(); + } + + public Set getScopedDeviceGroups() { + return this.scope == null ? null : this.scope.getGroup(); + } + + public Set getScopedDevice() { + return this.scope == null ? null : this.scope.getDevice(); + } + + public void setScope(ProfileScope scope) { + this.scope = scope; + } + + public User getWriter() { + return this.writer; + } + + public void setWriter(User writer) { + this.writer = writer; + } + + public void initApps() { + if (this.apps != null) { + this.apps.initInstallApp(); + this.apps.setInstall(this.apps.getInstallApp()); + } + + } + + public ProfileApps getApps() { + return this.apps; + } + + public List getInstallApps() { + if (this.apps == null) { + this.initApps(); + } + + return this.apps == null ? null : this.apps.getInstallApp(); + } + + public List getInstallUuids() { + if (this.apps == null) { + this.initApps(); + } + + return this.apps != null ? this.apps.getInstallUuids() : null; + } + + public ProfileApps.InstallApp getInstallApp(String packageName) { + if (this.apps == null) { + this.initApps(); + } + + return this.apps != null ? this.apps.getInstallApp(packageName) : null; + } + + public void setApps(ProfileApps apps) { + this.apps = apps; + } + + public boolean needOldFormat() { + return this.needOldFormat; + } + + public void setNeedOldFormat(boolean need) { + this.needOldFormat = need; + } + + public void setToOldFormat() { + if (this.apps != null) { + this.apps.setToOldFormat(); + } + + } + + public List getWhiteListPackages() { + return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null; + } + + public List getBlackListPackages() { + return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null; + } + + public List getOtas() { + return this.otas; + } + + public void setOtas(List otas) { + this.otas = otas; + } + + public boolean checkBuildDate() { + return this.getSettingAsBoolean("otas", "checkBuildDate", false); + } + + public DbObject getFiles() { + return this.files; + } + + public void setFiles(DbObject files) { + this.files = files; + } + + public DbObject getProgress() { + return this.progress; + } + + public void setProgress(DbObject progress) { + this.progress = progress; + } + + public DbObject getReference() { + return this.reference; + } + + public void setReference(DbObject reference) { + this.reference = reference; + } + + public void setReference(String key, Object data) { + if (data == null) { + if (this.reference != null) { + this.reference.remove(key); + } + } else if (this.reference == null) { + this.reference = new DbObject(key, data); + } else { + this.reference.put(key, data); + } + + } + + public void unsetDateTimeSettings() { + DbObject settings = this.getSettingsCategory(new String[]{"system", "dateTime"}); + if (settings != null) { + if (settings.containsKey("hourFormat")) { + settings.remove("hourFormat"); + } + + if (settings.size() > 0) { + this.setSetting("system", "dateTime", settings); + } else { + this.setSetting("system", "dateTime", (Object)null); + } + } + + } + + public void convertCustomSettingsForDevice() { + String[] categories = new String[]{"systemProperties", "globalSettings", "systemSettings", "secureSettings"}; + + for(String category : categories) { + Object settingValue = this.getSetting(category); + if (settingValue instanceof List) { + List> settings = (List)this.getSetting(category); + if (settings != null && !settings.isEmpty()) { + DbObject newSettings = new DbObject(); + settings.forEach((item) -> newSettings.append((String)item.get("key"), item.get("value"))); + this.setSetting(category, newSettings); + } + } else if (settingValue instanceof DbObject) { + this.setSetting(category, (UUID)null); + } + } + + if (this.getSettings().containsKey("midm")) { + boolean reboot = this.getSettingsCategory(new String[]{"midm"}).getBoolean("reboot", true); + DbObject systemSettings = this.getSettingsCategory(new String[]{"systemSettings"}); + if (systemSettings == null) { + systemSettings = new DbObject(); + } + + systemSettings.put("midmclient.reboot", Character.valueOf((char)(reboot ? '1' : '0'))); + } else if (this.settings.containsKey("otas") && (this.otas == null || this.otas.isEmpty())) { + this.settings.remove("otas"); + this.otas = null; + } + + } + + public boolean removeIfNoScope() { + return this.getProfile().getBoolean("removeIfNoScope", false); + } + + public boolean unscopeIfApplied() { + return this.getProfile().getBoolean("unscopeIfApplied", false); + } + + public void minify() { + super.minify(); + this.deviceProfileGroup = null; + this.scope = null; + this.writerUuid = null; + this.writer = null; + } + + public DeviceProfile clone() { + return (DeviceProfile)McJsonUtils.clone(this); + } +} diff --git a/src/main/java/com/midm/model/device/DeviceProfileGroup.java b/src/main/java/com/midm/model/device/DeviceProfileGroup.java new file mode 100644 index 0000000..724b45b --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceProfileGroup.java @@ -0,0 +1,57 @@ +package com.midm.model.device; + +import com.midm.model.GeneralProfile; +import java.util.List; +import java.util.UUID; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class DeviceProfileGroup extends GeneralProfile { + private UUID siteUuid; + private UUID parentUuid; + private Integer order; + @Transient + private Long deviceProfileNumbers; + private List children; + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public UUID getParentUuid() { + return this.parentUuid; + } + + public void setParentUuid(UUID parentUuid) { + this.parentUuid = parentUuid; + } + + public Integer getOrder() { + return this.order; + } + + public void setOrder(Integer order) { + this.order = order; + } + + public Long getDeviceProfileNumbers() { + return this.deviceProfileNumbers; + } + + public void setDeviceProfileNumbers(Long numbers) { + this.deviceProfileNumbers = numbers; + } + + public List getChildren() { + return this.children; + } + + public void setChildren(List children) { + this.children = children; + } +} diff --git a/src/main/java/com/midm/model/device/DeviceProfileState.java b/src/main/java/com/midm/model/device/DeviceProfileState.java new file mode 100644 index 0000000..0fcab1f --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceProfileState.java @@ -0,0 +1,155 @@ +package com.midm.model.device; + +import com.mitac.cell.db.DbObject; +import java.io.Serializable; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.CompoundIndexes; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@CompoundIndexes({@CompoundIndex( + def = "{'_id.deviceUuid': 1}" +), @CompoundIndex( + def = "{'_id.profileUuid': 1}" +)}) +public class DeviceProfileState { + public static final String STATE_IN_PROGRESS = "in_progress"; + public static final String STATE_DONE = "done"; + public static final String STATE_UNKNWON = "unknown"; + @Id + private Scoped scoped; + private long updated = -1L; + @Indexed + private String state = "unknown"; + private String applyFirstState = "unknown"; + @Indexed + private long applied; + @Transient + private DeviceReport report; + + public DeviceProfileState() { + } + + public DeviceProfileState(Device device, DeviceProfile profile) { + this.scoped = new Scoped(profile.getUuid(), device.getUuid()); + this.updated = profile.getUpdated().getTime(); + this.applied = (new Date()).getTime(); + } + + public DeviceProfileState(DeviceReport report) { + this.setReport(report); + } + + public Scoped getScoped() { + return this.scoped; + } + + public void setScoped(Scoped scoped) { + this.scoped = scoped; + } + + public UUID getProfileUuid() { + return this.getScoped().getProfileUuid(); + } + + public UUID getDeviceUuid() { + return this.getScoped().getDeviceUuid(); + } + + public long getUpdated() { + return this.updated; + } + + public void setUpdated(long updated) { + this.updated = updated; + } + + public String getState() { + return this.state; + } + + public boolean isDone() { + return this.state == null || this.state.equals("done"); + } + + public void setState(String state) { + this.state = state; + } + + public String getApplyFirstState() { + return this.applyFirstState; + } + + public boolean isApplyFirstDone() { + return this.applyFirstState != null && this.applyFirstState.equals("done"); + } + + public void setApplyFirstState(String applyFirstState) { + this.applyFirstState = applyFirstState; + } + + public long getApplied() { + return this.applied; + } + + public void setApplied(long applied) { + this.applied = applied; + this.setState("done"); + } + + public void setApplied(long applied, String state) { + this.state = state; + this.applied = applied; + } + + public void setApplied() { + this.applied = (new Date()).getTime(); + } + + public DeviceReport getReport() { + return this.report; + } + + public void setReport(DeviceReport report) { + this.report = report; + DbObject profile = report.getProperties().getDbObject(new String[]{"deviceProfile"}); + this.scoped = new Scoped(profile.getUuid("uuid"), report.getDeviceUuid()); + this.updated = profile.getLong("updated", -1L); + this.applied = profile.getLong("applied", -1L); + this.setState("done"); + } + + public static class Scoped implements Serializable { + private UUID profileUuid; + private UUID deviceUuid; + + public Scoped() { + } + + public Scoped(UUID profileUuid, UUID deviceUuid) { + this.profileUuid = profileUuid; + this.deviceUuid = deviceUuid; + } + + public UUID getProfileUuid() { + return this.profileUuid; + } + + public void setProfileUuid(UUID profileUuid) { + this.profileUuid = profileUuid; + } + + public UUID getDeviceUuid() { + return this.deviceUuid; + } + + public void setDeviceUuid(UUID deviceUuid) { + this.deviceUuid = deviceUuid; + } + } +} diff --git a/src/main/java/com/midm/model/device/DeviceReport.java b/src/main/java/com/midm/model/device/DeviceReport.java new file mode 100644 index 0000000..4e6c483 --- /dev/null +++ b/src/main/java/com/midm/model/device/DeviceReport.java @@ -0,0 +1,136 @@ +package com.midm.model.device; + +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McJsonUtils; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.CompoundIndexes; +import org.springframework.data.mongodb.core.mapping.Document; + +/** + * ====================================================================================== + * IoT 设备时序遥测上报数据模型 (DeviceReport) + * ====================================================================================== + * + *

【时序遥测存储与复合索引优化】 + * 1. 业务场景: + * - 采集移动受控设备的动态遥测快照(GPS地理坐标、传感器数值、网络质量、策略生效版本等)。 + * 2. 【高并发时序复合索引】: + * - `{'deviceUuid': 1, 'properties.location.time': -1}`: + * 按设备维度按时间倒序快速检索设备的历史运动轨迹,支撑地理围栏(Geo-fencing)与电子地图回放; + * - `{'properties.deviceProfile.uuid': 1, 'properties.deviceProfile.updated': 1}`: + * 用于统计各策略配置(DeviceProfile)在设备上的下发与部署成功率。 + * + * @author MiDM Core Platform Team + */ +@Document +@CompoundIndexes({@CompoundIndex( + def = "{'properties.deviceProfile.uuid':1, 'properties.deviceProfile.updated':1}" +), @CompoundIndex( + def = "{'deviceUuid':1, 'properties.location.time': -1}" +)}) +public class DeviceReport { + /** 报告记录全局主键 UUID */ + @Id + private UUID uuid; + + /** 关联的目标受控硬件主键 UUID */ + private UUID deviceUuid; + + /** 临时字段:设备序列号 */ + @Transient + private String serialNo; + + /** 动态遥测属性字典(包含 GPS 坐标:properties.location.latitude / longitude 等) */ + private DbObject properties; + + /** 终端边缘侧本地采样并生成该报文的时间戳 */ + private Date reportedAt; + + /** 云端服务端持久化写入数据库的系统时间戳 */ + private Date recordedAt; + + public DeviceReport() { + this.setRecordedAt(); + } + + public void init() { + this.setUuid(UUID.randomUUID()); + this.setReportedAt(new Date()); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public UUID getDeviceUuid() { + return this.deviceUuid; + } + + public void setDeviceUuid(UUID deviceUuid) { + this.deviceUuid = deviceUuid; + } + + public String getSerialNo() { + return this.serialNo; + } + + public void setSerialNo(String serialNo) { + this.serialNo = serialNo; + } + + public boolean hasProperties() { + return this.properties != null && !this.properties.isEmpty(); + } + + public DbObject getProperties() { + if (this.properties == null) { + this.properties = new DbObject(); + } + + return this.properties; + } + + public void setProperties(DbObject properties) { + this.properties = properties; + } + + public Date getReportedAt() { + return this.reportedAt; + } + + public void setReportedAt(Date reportedAt) { + this.reportedAt = reportedAt; + } + + public Date getRecordedAt() { + return this.recordedAt; + } + + public void setRecordedAt(Date recordedAt) { + this.recordedAt = recordedAt; + } + + public void setRecordedAt() { + this.recordedAt = new Date(); + } + + public void setProperty(String key, Object val) { + this.getProperties().append(key, val); + } + + public Object getProperty(String key) { + return this.getProperties().get(key); + } + + public String toString() { + return McJsonUtils.toJson(this); + } +} diff --git a/src/main/java/com/midm/model/device/ProfileApps.java b/src/main/java/com/midm/model/device/ProfileApps.java new file mode 100644 index 0000000..4baf3b3 --- /dev/null +++ b/src/main/java/com/midm/model/device/ProfileApps.java @@ -0,0 +1,289 @@ +package com.midm.model.device; + +import com.google.common.reflect.TypeToken; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.midm.model.file.AppFile; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McJsonUtils; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Field; + +public class ProfileApps { + private List install; + @Transient + @Expose( + serialize = false + ) + private List installApp; + private List uninstall; + @SerializedName("add_appwidget") + @Field("add_appwidget") + private List appWidget; + private List widget; + @SerializedName("grant_all") + @Field("grant_all") + private List grantAll; + private List disabled; + @SerializedName("wifi_only") + @Field("wifi_only") + private List wifiOnly; + @SerializedName("white_list") + @Field("white_list") + private List whiteList; + @SerializedName("black_list") + @Field("black_list") + private List blackList; + + public List getInstall() { + return this.install; + } + + public void setInstall(List install) { + this.install = install; + } + + public void setToOldFormat() { + this.install = this.getInstallUuids(); + } + + public List getInstallApp() { + if (this.installApp == null && this.install != null) { + this.initInstallApp(); + } + + return this.installApp; + } + + public void initInstallApp() { + if (this.install != null && !this.install.isEmpty()) { + if (this.install.get(0) instanceof InstallApp) { + this.installApp = this.install; + } else { + this.installApp = (List)McJsonUtils.toObject(McJsonUtils.toJsonElement(this.install), (new TypeToken() { + }).getType()); + this.install = this.installApp; + } + } + + } + + public void setInstallApp(List installApp) { + this.installApp = installApp; + } + + public boolean hasInstallApps() { + this.getInstallApp(); + return this.installApp != null && !this.installApp.isEmpty(); + } + + public InstallApp getInstallApp(String packageName) { + if (!this.hasInstallApps()) { + return null; + } else { + for(InstallApp app : this.installApp) { + if (packageName.equals(app.getPackageName())) { + return app; + } + } + + return null; + } + } + + public boolean removeInstallApp(UUID appUuid) { + if (this.hasInstallApps()) { + Iterator it = this.installApp.iterator(); + + while(it.hasNext()) { + if (((InstallApp)it.next()).uuid.equals(appUuid)) { + it.remove(); + return true; + } + } + } + + return false; + } + + public List getInstallUuids() { + return this.installApp != null ? (List)this.installApp.stream().map((app) -> app.getUuid()).collect(Collectors.toList()) : null; + } + + public List getUninstall() { + return this.toDbList(this.uninstall); + } + + public void setUninstall(List uninstall) { + this.uninstall = uninstall; + } + + public List getAppWidget() { + return this.appWidget; + } + + public void setAppWidget(List addAppWidget) { + this.appWidget = addAppWidget; + } + + public List getWidget() { + return this.widget; + } + + public void setWidget(List widget) { + this.widget = widget; + } + + public List getGrantAll() { + return this.toDbList(this.grantAll); + } + + public void setGrantAll(List grantAll) { + this.grantAll = grantAll; + } + + public List getDisabled() { + return this.toDbList(this.disabled); + } + + public void setDisabled(List disabled) { + this.disabled = disabled; + } + + public List getWifiOnly() { + return this.toDbList(this.wifiOnly); + } + + public void setWifiOnly(List wifiOnly) { + this.wifiOnly = wifiOnly; + } + + public List getWhiteList() { + return this.toDbList(this.whiteList); + } + + public void setWhiteList(List whiteList) { + this.whiteList = whiteList; + } + + public List getBlackList() { + return this.toDbList(this.blackList); + } + + public void setBlackList(List blackList) { + this.blackList = blackList; + } + + public List getPackageList(List apps) { + return apps != null ? (List)apps.stream().map((app) -> app.getString("package")).collect(Collectors.toList()) : null; + } + + public boolean isEmpty() { + return (this.install == null || this.install.isEmpty()) && (this.uninstall == null || this.uninstall.isEmpty()) && (this.appWidget == null || this.appWidget.isEmpty()) && (this.widget == null || this.widget.isEmpty()) && (this.grantAll == null || this.grantAll.isEmpty()) && (this.disabled == null || this.disabled.isEmpty()) && (this.wifiOnly == null || this.wifiOnly.isEmpty()) && (this.whiteList == null || this.whiteList.isEmpty()) && (this.blackList == null || this.blackList.isEmpty()); + } + + private List toDbList(List list) { + if (list != null && !list.isEmpty()) { + List dbList = new ArrayList(); + list.forEach((item) -> { + if (item instanceof DbObject) { + dbList.add((DbObject)item); + } else if (item instanceof Map) { + dbList.add(new DbObject((Map)item)); + } + + }); + return dbList; + } else { + return null; + } + } + + public static class InstallApp { + private UUID uuid; + private String packageName; + @SerializedName("silent_install") + @Field("silent_install") + private Boolean silentInstall = true; + @SerializedName("grant_all") + @Field("grant_all") + private Boolean grantAll = false; + @SerializedName("starts_on_update") + @Field("starts_on_update") + private Boolean startsOnUpdate = false; + @SerializedName("reboots_on_update") + @Field("reboots_on_update") + private Boolean rebootsOnUpdate = false; + + public InstallApp() { + } + + public InstallApp(AppFile appFile) { + this.uuid = appFile.getFileUuid(); + this.packageName = appFile.getPackageName(); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public String getPackageName() { + return this.packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public Boolean getSilentInstall() { + return this.silentInstall; + } + + public void setSilentInstall(Boolean silentInstall) { + this.silentInstall = silentInstall; + } + + public Boolean getGrantAll() { + return this.grantAll; + } + + public void setGrantAll(Boolean grantAll) { + this.grantAll = grantAll; + } + + public Boolean getStartsOnUpdate() { + return this.startsOnUpdate; + } + + public void setStartsOnUpdate(Boolean startsOnUpdate) { + this.startsOnUpdate = startsOnUpdate; + } + + public Boolean getRebootsOnUpdate() { + return this.rebootsOnUpdate; + } + + public void setRebootsOnUpdate(Boolean rebootsOnUpdate) { + this.rebootsOnUpdate = rebootsOnUpdate; + } + + public boolean equals(Object obj) { + if (!(obj instanceof InstallApp)) { + return false; + } else { + InstallApp installApp = (InstallApp)obj; + return this.uuid.equals(installApp.uuid) && this.packageName.equals(installApp.packageName) && this.silentInstall == installApp.silentInstall && this.grantAll == installApp.grantAll && this.startsOnUpdate == installApp.startsOnUpdate && this.rebootsOnUpdate == installApp.rebootsOnUpdate; + } + } + } +} diff --git a/src/main/java/com/midm/model/device/ProfileScope.java b/src/main/java/com/midm/model/device/ProfileScope.java new file mode 100644 index 0000000..d13eefa --- /dev/null +++ b/src/main/java/com/midm/model/device/ProfileScope.java @@ -0,0 +1,69 @@ +package com.midm.model.device; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +public class ProfileScope { + Set group; + Set device; + Set userGroup; + + public Set getGroup() { + return this.group; + } + + public void setGroup(Set group) { + this.group = group; + } + + public void addGroup(UUID groupUuid) { + if (this.group == null) { + this.group = new HashSet(); + this.group.add(groupUuid); + } + + } + + public void removeGroup(UUID groupUuid) { + if (this.group != null) { + this.group.remove(groupUuid); + } + + } + + public Set getDevice() { + return this.device; + } + + public void setDevice(Set device) { + this.device = device; + } + + public void addDevice(String serialNo) { + if (this.device == null) { + this.device = new HashSet(); + this.device.add(serialNo); + } + + } + + public void removeDevice(String serialNo) { + if (this.device != null) { + this.device.remove(serialNo); + } + + } + + public Set getUserGroup() { + return this.userGroup; + } + + public void setUserGroup(Set userGroup) { + this.userGroup = userGroup; + } + + public boolean hasScoped() { + return this.group != null && !this.group.isEmpty() || this.device != null && !this.device.isEmpty() || this.userGroup != null && !this.userGroup.isEmpty(); + } +} diff --git a/src/main/java/com/midm/model/device/ReconnectMonitor.java b/src/main/java/com/midm/model/device/ReconnectMonitor.java new file mode 100644 index 0000000..e248fd2 --- /dev/null +++ b/src/main/java/com/midm/model/device/ReconnectMonitor.java @@ -0,0 +1,164 @@ +package com.midm.model.device; + +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import java.util.Date; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; +import org.joda.time.LocalDateTime; + +public class ReconnectMonitor { + private static final int BLOCKING_HOURS = 12; + private static final int RECONNECT_FOR = 10; + private Device device; + private Date startedAt; + private long prevMins; + private int count; + private int total; + private Date blockedAt; + private Date unblockAt; + private Timer unblockTimer; + private OnAbusedListener listener; + + public ReconnectMonitor(Device device, OnAbusedListener listener) { + this.device = device; + this.listener = listener; + this.init(); + } + + private void init() { + this.startedAt = new Date(); + this.blockedAt = null; + this.unblockAt = null; + this.prevMins = this.getCurMins(); + this.total = this.count = 1; + } + + public Device getDevice() { + return this.device; + } + + public UUID getDeviceUuid() { + return this.device.getUuid(); + } + + public Date getStartedAt() { + return this.startedAt; + } + + public Date getBlockedAt() { + return this.blockedAt; + } + + public Date getUnblockAt() { + return this.unblockAt; + } + + public int getCount() { + return this.count; + } + + public int getTotal() { + return this.total; + } + + public void connected() { + long curMins = this.getCurMins(); + long gap = curMins - this.prevMins; + if (gap <= 1L) { + ++this.total; + if (gap == 1L) { + ++this.count; + this.prevMins = curMins; + if (this.count >= 10) { + this.blockedAt = new Date(); + this.onAbused(); + } + } + } else { + this.init(); + } + + } + + public boolean isBlocked() { + return this.blockedAt != null; + } + + public void block() { + this.blockedAt = new Date(); + this.unblockAt = (new LocalDateTime(this.blockedAt)).plusHours(12).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).toDate(); + this.startUnblockTimer(); + } + + public void block(Device device) { + if (device.isBlocked()) { + DbObject blockedState = device.getStates().getDbObject(new String[]{"blocked"}); + this.blockedAt = blockedState.getDate("from"); + this.unblockAt = blockedState.getDate("to"); + if (this.unblockAt.getTime() < (new Date()).getTime()) { + this.unblock((User)null); + } else { + this.startUnblockTimer(); + } + } else { + this.block(); + } + + } + + private void startUnblockTimer() { + this.stopUnblockTimer(); + String var10003 = this.device.getUuid().toString(); + this.unblockTimer = new Timer(var10003 + (new Date()).getTime()); + this.unblockTimer.schedule(new TimerTask() { + public void run() { + ReconnectMonitor.this.unblock((User)null); + } + }, this.unblockAt); + } + + private void stopUnblockTimer() { + if (this.unblockTimer != null) { + try { + this.unblockTimer.cancel(); + this.unblockTimer.purge(); + this.unblockTimer = null; + } catch (Exception var2) { + } + } + + } + + public void unblock(User user) { + this.stopUnblockTimer(); + this.startedAt = null; + this.blockedAt = null; + this.unblockAt = null; + this.prevMins = 0L; + this.total = this.count = 0; + if (this.listener != null) { + this.listener.onUnblocked(this, user); + } + + } + + private void onAbused() { + this.block(); + if (this.listener != null) { + this.listener.onAbused(this); + } + + } + + private long getCurMins() { + return (new Date()).getTime() / 60000L; + } + + public interface OnAbusedListener { + void onAbused(ReconnectMonitor monitor); + + void onUnblocked(ReconnectMonitor monitor, User user); + } +} diff --git a/src/main/java/com/midm/model/file/AppFile.java b/src/main/java/com/midm/model/file/AppFile.java new file mode 100644 index 0000000..45c9e0a --- /dev/null +++ b/src/main/java/com/midm/model/file/AppFile.java @@ -0,0 +1,229 @@ +package com.midm.model.file; + +import com.google.api.client.util.Strings; +import com.google.gson.annotations.Expose; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McApkFile; +import com.mitac.cell.io.McFile; +import java.util.List; +import java.util.UUID; +import net.dongliu.apk.parser.bean.ApkMeta; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class AppFile extends BaseFile { + private DbObject appInfo; + private DbObject updateOptions; + @Transient + @Expose( + serialize = false + ) + private boolean generateIcon; + + public AppFile() { + this.generateIcon = true; + } + + public AppFile(User user, UUID fileUuid, McFile file) { + this(user, fileUuid, file, true); + } + + public AppFile(User user, UUID fileUuid, McFile file, boolean generateIcon) { + super(user, fileUuid, file); + this.generateIcon = true; + this.generateIcon = generateIcon; + this.setAppInfo(file); + } + + public boolean isApk() { + return !Strings.isNullOrEmpty(this.getPackageName()); + } + + public boolean hasSystemPermission() { + return "android.uid.system".equals(this.getSharedUserId()); + } + + public DbObject getAppInfo() { + if (this.appInfo == null) { + this.appInfo = new DbObject(); + } + + return this.appInfo; + } + + public void setAppInfo(DbObject appInfo) { + this.appInfo = appInfo; + } + + public void setAppInfo(String key, Object value) { + this.getAppInfo().append(key, value); + } + + public DbObject getUpdateOptions() { + if (this.updateOptions == null) { + this.updateOptions = new DbObject(); + } + + return this.updateOptions; + } + + public void setUpdateOptions(DbObject updateOptions) { + this.updateOptions = updateOptions; + } + + public void setUpdateOptions(String key, Object value) { + this.getUpdateOptions().append(key, value); + } + + public boolean isMitacApp() { + return this.getPackageName().toLowerCase().contains("mitac"); + } + + public String getPackageName() { + return this.getAppInfo().getString("packageName"); + } + + public void setPackageName(String packageName) { + this.setAppInfo("packageName", packageName); + } + + public String getSharedUserId() { + return this.getAppInfo().getString("sharedUid"); + } + + public void setSharedUserId(String sharedUid) { + if (!Strings.isNullOrEmpty(sharedUid)) { + this.setAppInfo("sharedUid", sharedUid); + } + + } + + public String getLabel() { + return this.getAppInfo().getString("label"); + } + + public void setLabel(String label) { + this.setAppInfo("label", label); + } + + public String getIconName() { + return this.getAppInfo().getString("iconName"); + } + + public void setIconName(String iconName) { + this.setAppInfo("iconName", iconName); + } + + public long getVersionCode() { + return this.getAppInfo().getLong("versionCode"); + } + + public void setVersionCode(long versionCode) { + this.setAppInfo("versionCode", versionCode); + } + + public String getVersionName() { + return this.getAppInfo().getString("versionName"); + } + + public void setVersionName(String versionName) { + this.setAppInfo("versionName", versionName); + } + + public int getMinSdkVersion() { + return this.getAppInfo().getInteger("minSdkVersion", -1); + } + + public void setMinSdkVersion(String minSdkVersion) { + if (!Strings.isNullOrEmpty(minSdkVersion)) { + this.setMinSdkVersion(Integer.parseInt(minSdkVersion)); + } + + } + + public void setMinSdkVersion(int minSdkVersion) { + this.setAppInfo("minSdkVersion", minSdkVersion); + } + + public int getMaxSdkVersion() { + return this.getAppInfo().getInteger("maxSdkVersion", -1); + } + + public void setMaxSdkVersion(String maxSdkVersion) { + if (!Strings.isNullOrEmpty(maxSdkVersion)) { + this.setAppInfo("maxSdkVersion", Integer.parseInt(maxSdkVersion)); + } + + } + + public int getTargetSdkVersion() { + return this.getAppInfo().getInteger("targetSdkVersion", -1); + } + + public void setTargetSdkVersion(String targetSdkVersion) { + if (Strings.isNullOrEmpty(targetSdkVersion)) { + this.getAppInfo().remove("targetSdkVersion"); + } else { + this.setAppInfo("targetSdkVersion", Integer.parseInt(targetSdkVersion)); + } + + } + + public List getUserPermission() { + return this.getAppInfo().getList("userPermission", String.class); + } + + public void setUserPermission(List userPermission) { + this.setAppInfo("userPermission", userPermission); + } + + public String getCertMd5() { + return this.getAppInfo().getString("certMd5"); + } + + public void setCertMd5(String certMd5) { + if (!Strings.isNullOrEmpty(certMd5)) { + this.setAppInfo("certMd5", certMd5); + } + + } + + public void setAppInfo(McFile file) { + try { + McApkFile apkFile = new McApkFile(file); + ApkMeta meta = apkFile.getApkMeta(); + this.setSharedUserId(meta.getSharedUserId()); + this.setPackageName(meta.getPackageName()); + String label = meta.getLabel(); + if (Strings.isNullOrEmpty(label)) { + label = meta.getPackageName(); + } + + this.setLabel(label); + this.setVersionCode(meta.getVersionCode()); + this.setVersionName(meta.getVersionName()); + this.setUserPermission(meta.getUsesPermissions()); + this.setMinSdkVersion(meta.getMinSdkVersion()); + this.setMaxSdkVersion(meta.getMaxSdkVersion()); + this.setTargetSdkVersion(meta.getTargetSdkVersion()); + this.setCertMd5(apkFile.getCertMd5()); + this.setName(this.getLabel()); + if (this.generateIcon) { + apkFile.saveIcon(file.getPath() + ".png"); + } + + apkFile.close(); + } catch (Exception var5) { + } + + } + + public void minify() { + super.minify(); + this.setUserPermission((List)null); + this.setTargetSdkVersion((String)null); + this.setVersionName((String)null); + } +} diff --git a/src/main/java/com/midm/model/file/BaseFile.java b/src/main/java/com/midm/model/file/BaseFile.java new file mode 100644 index 0000000..30cf45b --- /dev/null +++ b/src/main/java/com/midm/model/file/BaseFile.java @@ -0,0 +1,279 @@ +package com.midm.model.file; + +import com.google.common.base.Strings; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McFile; +import java.util.Arrays; +import java.util.Date; +import java.util.Map; +import java.util.UUID; +import org.apache.tika.Tika; +import org.joda.time.LocalDateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class BaseFile { + @Id + protected UUID fileUuid; + protected UUID userUuid; + @Indexed + protected UUID siteUuid; + protected DbObject fileInfo; + protected DbObject extra; + protected String name; + protected boolean enabled = true; + protected Date lastUpdated; + protected Date registeredAt; + + public BaseFile() { + } + + public BaseFile(User user, UUID fileUuid, McFile file) { + this.setUserUuid(user); + this.setFileUuid(fileUuid); + this.setFileInfo(file); + this.initRegisteredAt(); + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public UUID getFileUuid() { + return this.fileUuid; + } + + public void setFileUuid(UUID uid) { + this.fileUuid = uid; + } + + public UUID getUserUuid() { + return this.userUuid; + } + + public void setUserUuid(UUID uid) { + this.userUuid = uid; + } + + public void setUserUuid(User user) { + if (user != null) { + this.userUuid = user.getUuid(); + } + + } + + public DbObject getFileInfo() { + if (this.fileInfo == null) { + this.fileInfo = new DbObject(); + } + + return this.fileInfo; + } + + public String getFileInfoAsString(String key) { + if (this.fileInfo == null) { + this.fileInfo = new DbObject(); + } + + return this.fileInfo.getString(key); + } + + public void removeFileInfo() { + this.fileInfo = null; + } + + public void setFileInfo(DbObject fileInfo) { + this.fileInfo = fileInfo; + } + + public void setFileInfo(McFile file) { + if (file.exists()) { + this.setLength(file.length()); + this.setChecksum(file.getCrcChecksum()); + this.setLastModified(file.lastModified()); + } + + } + + public DbObject getExtra() { + return this.extra; + } + + public void setExtra(DbObject extra) { + this.extra = extra; + } + + public void setExtra(Map parameters) { + if (parameters != null) { + if (this.extra == null) { + this.extra = new DbObject(); + } + + parameters.forEach((key, value) -> { + if (value.length > 0 && key.startsWith("extra.")) { + this.extra.put(key.substring(6), value.length == 1 ? value[0] : Arrays.asList(value)); + } + + }); + } + + } + + public boolean getEnabled() { + return this.enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFileName() { + return this.getFileInfo().getString("fileName"); + } + + public void setFileName(String fileName) { + this.setFileInfo("fileName", fileName); + } + + public String getContentType() { + String contentType = this.getFileInfo().getString("contentType"); + if (Strings.isNullOrEmpty(contentType)) { + contentType = (new Tika()).detect(this.getFileName()); + this.setType(contentType); + } + + return contentType; + } + + public void setType(String contentType) { + this.setFileInfo("contentType", contentType); + } + + public long getLength() { + return this.getFileInfo().getLong("length"); + } + + public void setLength(long length) { + this.setFileInfo("length", length); + } + + public long getChecksum() { + return this.getFileInfo().getLong("checksum"); + } + + public void setChecksum(long checksum) { + this.setFileInfo("checksum", checksum); + } + + public long getLastModified() { + return this.getFileInfo().getLong("lastModified"); + } + + public void setLastModified(long lastModified) { + if (lastModified <= 0L) { + lastModified = (new Date()).getTime(); + } + + this.setFileInfo("lastModified", lastModified); + } + + public void setFileInfo(String key, Object value) { + this.getFileInfo().append(key, value); + } + + public void setFileUrl(String url) { + this.setFileInfo("fileUrl", url); + } + + public long getUrlExpiry() { + Date expiry = this.getFileInfo().getDate("urlExpiry"); + return expiry == null ? -1L : expiry.getTime(); + } + + public void setCloudUrl(String url) { + this.setFileInfo("fileUrl", url); + Date expiry = LocalDateTime.now().plusDays(6).toDate(); + this.setFileInfo("urlExpiry", expiry); + } + + public boolean hasFileUrl() { + boolean hasUrl = this.getFileInfo().containsKey("fileUrl"); + if (hasUrl && this.getFileInfo().containsKey("urlExpiry")) { + hasUrl = this.getFileInfo().getDate("urlExpiry").after(new Date()); + if (!hasUrl) { + this.getFileInfo().remove("fileUrl"); + this.getFileInfo().remove("urlExpiry"); + } + } + + return hasUrl; + } + + public String getFileUrl() { + return this.getFileInfoAsString("fileUrl"); + } + + public boolean hasIconUrl() { + boolean hasUrl = this.getFileInfo().containsKey("iconUrl"); + if (hasUrl && this.getFileInfo().containsKey("iconExpiry")) { + hasUrl = this.getFileInfo().getDate("iconExpiry").after(new Date()); + if (!hasUrl) { + this.getFileInfo().remove("iconUrl"); + this.getFileInfo().remove("iconExpiry"); + } + } + + return hasUrl; + } + + public void setIconUrl(String url) { + this.setFileInfo("iconUrl", url); + Date expiry = LocalDateTime.now().plusDays(6).toDate(); + this.setFileInfo("iconExpiry", expiry); + } + + public String getIconUrl() { + return this.getFileInfoAsString("iconUrl"); + } + + public Date getLastUpdated() { + return this.lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public Date getRegisteredAt() { + return this.registeredAt; + } + + public void setRegisteredAt(Date registeredAt) { + this.registeredAt = registeredAt; + } + + public void initRegisteredAt() { + this.setRegisteredAt(new Date()); + this.setLastUpdated(this.getRegisteredAt()); + } + + public void minify() { + this.userUuid = null; + this.registeredAt = null; + } +} diff --git a/src/main/java/com/midm/model/file/DeployOption.java b/src/main/java/com/midm/model/file/DeployOption.java new file mode 100644 index 0000000..bc7455a --- /dev/null +++ b/src/main/java/com/midm/model/file/DeployOption.java @@ -0,0 +1,81 @@ +package com.midm.model.file; + +public class DeployOption { + public static final String PROPERTY_DEFAULT = "default"; + public static final String PROPERTY_FORCE_TO_DOWNLOAD = "force_to_download"; + public static final String PROPERTY_FORCE_TO_INSTALL = "force_to_install"; + public static final String PROPERTY_SAVE_AS = "save_as"; + public static final String PROPERTY_KEEP_BACKUP = "keep_backgup"; + private boolean isDefault; + private boolean uninstallFirst; + private boolean keepData; + private boolean forceToDownload; + private boolean foreceToInstall; + private String saveTo; + private boolean keepBackup; + private boolean isUserMode; + + public boolean getIsDefault() { + return this.isDefault; + } + + public void setIsDefault(boolean isDefault) { + this.isDefault = isDefault; + } + + public boolean getUninstallFirst() { + return this.uninstallFirst; + } + + public void setUninstallFirst(boolean uninstallFirst) { + this.uninstallFirst = uninstallFirst; + } + + public boolean getKeepData() { + return this.keepData; + } + + public void setKeepData(boolean keepData) { + this.keepData = keepData; + } + + public boolean getForceToDownload() { + return this.forceToDownload; + } + + public void setForceToDownload(boolean forceToDownload) { + this.forceToDownload = forceToDownload; + } + + public boolean getForeceToInstall() { + return this.foreceToInstall; + } + + public void setForeceToInstall(boolean foreceToInstall) { + this.foreceToInstall = foreceToInstall; + } + + public String getSaveTo() { + return this.saveTo; + } + + public void setSaveTo(String saveTo) { + this.saveTo = saveTo; + } + + public boolean getKeepBackup() { + return this.keepBackup; + } + + public void setKeepBackup(boolean keepBackup) { + this.keepBackup = keepBackup; + } + + public boolean getIsUserMode() { + return this.isUserMode; + } + + public void setIsUserMode(boolean isUserMode) { + this.isUserMode = isUserMode; + } +} diff --git a/src/main/java/com/midm/model/file/FILE_TYPE.java b/src/main/java/com/midm/model/file/FILE_TYPE.java new file mode 100644 index 0000000..3e6efb0 --- /dev/null +++ b/src/main/java/com/midm/model/file/FILE_TYPE.java @@ -0,0 +1,9 @@ +package com.midm.model.file; + +public enum FILE_TYPE { + OTA, + REGION, + APK, + FILE, + UNKNOWN; +} diff --git a/src/main/java/com/midm/model/file/OtaFile.java b/src/main/java/com/midm/model/file/OtaFile.java new file mode 100644 index 0000000..10d2454 --- /dev/null +++ b/src/main/java/com/midm/model/file/OtaFile.java @@ -0,0 +1,784 @@ +package com.midm.model.file; + +import com.google.common.base.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McFile; +import com.mitac.cell.security.McOtaCert; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; +import org.apache.commons.io.IOUtils; +import org.springframework.data.mongodb.core.mapping.Document; + +/** + * ====================================================================================== + * Android / 嵌入式系统 OTA 固件镜像模型 (OtaFile) + * ====================================================================================== + * + *

【IoT 固件空中升级 (FOTA) 核心实现】 + * 1. 业务功能: + * - 管理受控终端的完整系统固件镜像(System Image / Full OTA)与区域增量镜像(Region Image / Incremental OTA)。 + * 2. 【固件安全与包结构解析】: + * - 自动解包并解析 Android Recovery 规范的标准固件 ZIP 包结构: + * - `META-INF/com/google/android/updater-script`: 固件升级执行脚本; + * - `system/build.prop`: 提取目标硬件型号、Android 操作系统版本、编译日期(build_date)、基带版本等; + * - `META-INF/com/android/otacert`: 嵌入式固件发布签名证书,校验固件是否由官方私钥签发; + * - `META-INF/com/android/metadata`: 提取差分升级的前置版本与兼容约束。 + * 3. 硬件兼容性矩阵(SKU Matching): + * - 严格匹配终端出厂 SKU,防止跨机型错刷固件导致设备“变砖”(Bricking)。 + * + * @author MiDM Core Platform Team + */ +@Document +public class OtaFile extends BaseFile implements Comparable { + /** Android Recovery 固件升级脚本入口 */ + private static final String ENTRY_META_INF = "META-INF/com/"; + private static final String ENTRY_UPDATE_SCRIPT = "META-INF/com/google/android/updater-script"; + + /** Android 操作系统属性字典路径(包含型号、Build版本、指纹等关键参数) */ + private static final String ENTRY_BUILD_PROP = "system/build.prop"; + + /** 固件合法性验签 X.509 官方证书路径 */ + private static final String ENTRY_OTA_CERT = "META-INF/com/android/otacert"; + + /** OTA 元数据配置文件(版本区间、差分基线版本等) */ + private static final String ENTRY_METADATA = "META-INF/com/android/metadata"; + private static final String ENTRY_UPDATE_INFO = "META-INF/com/android/update_info"; + + /** 解析固件包后提取的硬件规格与构建元数据字典 */ + private DbObject otaInfo; + + public OtaFile() { + } + + public OtaFile(User user, UUID fileUuid, McFile file) { + super(user, fileUuid, file); + this.setOtaInfo(file); + } + + public boolean isOtaImage() { + if (Strings.isNullOrEmpty(this.getProductId()) && Strings.isNullOrEmpty(this.getDeviceId())) { + return false; + } else { + return this.isRegionImage() ? true : !Strings.isNullOrEmpty(this.getSkuId()); + } + } + + public DbObject getOtaInfo() { + if (this.otaInfo == null) { + this.otaInfo = new DbObject(); + } + + return this.otaInfo; + } + + public void setOtaInfo(DbObject otaInfo) { + this.otaInfo = otaInfo; + } + + public void setOtaInfo(String key, Object value) { + this.getOtaInfo().append(key, value); + } + + public void setOtaInfo(McFile file) { + try { + this.retrieveBuildInfo(new ZipFile(file)); + } catch (Exception var3) { + } + + } + + public String getType() { + return this.getOtaInfo().getString("type", "system"); + } + + public boolean isSystemImage() { + return this.getType().equals("system"); + } + + public boolean isRegionImage() { + return this.getType().equals("region"); + } + + public boolean isModemImage() { + return this.getType().equals("modem"); + } + + public boolean isAbUpdate() { + return this.getOtaInfo().getBoolean("abUpdate", false); + } + + public boolean isPartial() { + return this.getOtaInfo().containsKey("preBuild"); + } + + public void setType(String type) { + if (type.toLowerCase().equals("base")) { + type = "system"; + } + + this.getOtaInfo().put("type", type); + } + + public void setAbUpdate(boolean abUpdate) { + this.getOtaInfo().put("abUpdate", abUpdate); + } + + public long getBuildDate() { + return this.getOtaInfo().getLong("buildDate", -1L); + } + + public void setBuildDate(long date) { + this.setOtaInfo("buildDate", date); + } + + public int getSdkLevel() { + return this.getOtaInfo().getInteger("sdk", -1); + } + + public void setSdkLevel(int level) { + this.setOtaInfo("sdk", level); + } + + public long getPostBuildDate() { + return this.getOtaInfo().getLong("postBuildDate", -1L); + } + + public void setPostBuildDate(long date) { + this.setOtaInfo("postBuildDate", date); + } + + public String getProductId() { + return this.getOtaInfo().getString("productId"); + } + + public void setProductId(String productId) { + this.setOtaInfo("productId", productId); + } + + public String getTargetProduct() { + return this.getOtaInfo().getString("targetProduct"); + } + + public void setTargetProduct(String productId) { + this.setOtaInfo("targetProduct", productId); + } + + public String getSkuId() { + return this.getOtaInfo().getString("skuId"); + } + + public void setSkuId(String skuId) { + this.setOtaInfo("skuId", skuId); + } + + public boolean hasCompatibleSkuIds() { + List ids = this.getOtaInfo().getList("compatibleSkuIds", String.class); + return ids != null && ids.size() > 0; + } + + public List getCompatibleSkuIds() { + return this.getOtaInfo().getList("compatibleSkuIds", String.class); + } + + public boolean isCompatibleSkuId(String skuId) { + if (Strings.isNullOrEmpty(skuId)) { + return false; + } else { + String curSkuId = this.getSkuId(); + if (skuId.equals(curSkuId)) { + return true; + } else { + List compatibleSkuIds = this.getCompatibleSkuIds(); + return compatibleSkuIds != null && compatibleSkuIds.contains(skuId); + } + } + } + + public void setCompatibleSkuIds(String skuIds) { + if (!Strings.isNullOrEmpty(skuIds)) { + String[] ids = skuIds.split("\\s*,\\s*"); + if (ids != null && ids.length > 0) { + this.setOtaInfo("compatibleSkuIds", Arrays.asList(ids)); + } + } + + } + + public String getDeviceId() { + return this.getOtaInfo().getString("deviceId"); + } + + public void setDeviceId(String deviceId) { + this.setOtaInfo("deviceId", deviceId); + } + + public String getDisplayId() { + return this.getOtaInfo().getString("displayId"); + } + + public void setDisplayId(String displayId) { + this.setOtaInfo("displayId", displayId); + } + + public void setProductDisplayId(String displayId) { + this.setOtaInfo("productDisplayId", displayId); + } + + public String getPreDisplayId() { + return this.getOtaInfo().getString("preDisplayId"); + } + + public void setPreDisplayId(String displayId) { + this.setOtaInfo("preDisplayId", displayId); + } + + public static String parseSkuId(String displayId) { + if (displayId != null) { + int startIndex = displayId.indexOf(46); + ++startIndex; + startIndex = displayId.indexOf(46, startIndex); + if (startIndex > 0) { + int endIndex = displayId.indexOf(46, startIndex + 1); + if (endIndex > startIndex) { + ++startIndex; + return displayId.substring(startIndex, endIndex); + } + } + } + + return null; + } + + public String getBrand() { + return this.getOtaInfo().getString("brand"); + } + + public void setBrand(String brand) { + this.setOtaInfo("brand", brand); + } + + public String getCustomer() { + return this.getOtaInfo().getString("customer"); + } + + public void setCustomer(String customer) { + this.setOtaInfo("customer", customer); + } + + public String getCustomerId() { + return this.getOtaInfo().getString("customerId"); + } + + public void setCustomerId(String customerId) { + this.setOtaInfo("customerId", customerId); + } + + public String getPartNo() { + return this.getOtaInfo().getString("partNo"); + } + + public void setPartNo(String partNo) { + this.setOtaInfo("partNo", partNo); + } + + public String getOsVersion() { + return this.getOtaInfo().getString("osVersion"); + } + + public void setOsVersion(String version) { + this.setOtaInfo("osVersion", version); + } + + public String getScriptVersion() { + return this.getOtaInfo().getString("scriptVersion"); + } + + public void setScriptVersion(String partNo) { + this.setOtaInfo("scriptVersion", partNo); + } + + public String getReleaseVersion() { + return this.getOtaInfo().getString("releaseVersion"); + } + + public void setReleaseVersion(String partNo) { + this.setOtaInfo("releaseVersion", partNo); + } + + public String getMarketName1() { + return this.getOtaInfo().getString("marketName1"); + } + + public void setMarketName1(String name) { + this.setOtaInfo("marketName1", name); + } + + public String getMarketName2() { + return this.getOtaInfo().getString("marketName2"); + } + + public void setMarketName2(String name) { + this.setOtaInfo("marketName2", name); + } + + public String getSecurityPatchLevel() { + return this.getOtaInfo().getString("securityPatch"); + } + + public void setSecurityPatchLevel(String level) { + this.setOtaInfo("securityPatch", level); + } + + public String getBuildType() { + return this.getOtaInfo().getString("buildType"); + } + + public void setBuildType(String buildType) { + this.setOtaInfo("buildType", buildType); + } + + public String getBuildTags() { + return this.getOtaInfo().getString("buildTags"); + } + + public void setBuildTags(String buildTags) { + this.setOtaInfo("buildTags", buildTags); + } + + public String getPreBuild() { + return this.getOtaInfo().getString("preBuild"); + } + + public void setPreBuild(String value) { + this.setOtaInfo("preBuild", value); + } + + public String getOtaCertHash() { + return this.getOtaInfo().getString("otaCert"); + } + + public void setOtaCertHash(String hash) { + this.setOtaInfo("otaCert", hash); + } + + public String getModemSku() { + return this.getOtaInfo().getString("modemSku"); + } + + public void setModemSku(String hash) { + this.setOtaInfo("modemSku", hash); + } + + public String getModemFirmwareVersion() { + return this.getOtaInfo().getString("modemFirmwareVersion"); + } + + public void setModemFirmwareVersion(String hash) { + this.setOtaInfo("modemFirmwareVersion", hash); + } + + public String getModemFirmwareLongVersion() { + return this.getOtaInfo().getString("modemFirmwareLongVersion"); + } + + public void setModemFirmwareLongVersion(String hash) { + this.setOtaInfo("modemFirmwareLongVersion", hash); + } + + private void retrieveBuildInfo(ZipFile zipFile) { + try { + Enumeration entries = zipFile.entries(); + ZipEntry bodyEntry = null; + boolean isAbImage = false; + + while(entries.hasMoreElements()) { + ZipEntry entry = (ZipEntry)entries.nextElement(); + if (entry.getName().endsWith(".zip")) { + bodyEntry = entry; + } else if (entry.getName().endsWith(".sh")) { + isAbImage = true; + } + } + + if (isAbImage && bodyEntry != null) { + InputStream input = zipFile.getInputStream(bodyEntry); + + ZipInputStream zipBody; + ZipEntry entry; + for(zipBody = new ZipInputStream(input); (entry = zipBody.getNextEntry()) != null; zipBody.closeEntry()) { + String entryName = entry.getName(); + if (entryName.equals("META-INF/com/android/metadata")) { + this.dispatchProp(zipBody); + } else if (entryName.equals("META-INF/com/android/update_info")) { + this.dispatchJson(zipBody); + } else if (entryName.equals("META-INF/com/android/otacert")) { + this.dispatchOtaCert(zipBody); + } + } + + zipBody.close(); + input.close(); + } else { + ZipEntry udpateInfoEntry = zipFile.getEntry("META-INF/com/android/update_info"); + if (udpateInfoEntry != null) { + this.dispatchJson(zipFile.getInputStream(udpateInfoEntry)); + this.setType("region"); + } + + ZipEntry metaDataEntry = zipFile.getEntry("META-INF/com/android/metadata"); + if (metaDataEntry != null) { + this.dispatchProp(zipFile.getInputStream(metaDataEntry)); + } + + ZipEntry updateScriptEntry = zipFile.getEntry("META-INF/com/google/android/updater-script"); + if (updateScriptEntry != null) { + this.dispatchUpdaterScript(zipFile.getInputStream(updateScriptEntry)); + } + + ZipEntry otaCertEntry = zipFile.getEntry("META-INF/com/android/otacert"); + if (otaCertEntry != null) { + InputStream otaInput = zipFile.getInputStream(otaCertEntry); + this.dispatchOtaCert(otaInput); + otaInput.close(); + } + + ZipEntry buildPropEntry = zipFile.getEntry("system/build.prop"); + if (buildPropEntry != null) { + this.dispatchProp(zipFile.getInputStream(buildPropEntry)); + } + + zipFile.close(); + if (!Strings.isNullOrEmpty(this.getDisplayId()) && this.isRegionImage()) { + this.setDisplayId(String.format("%s_%s_%s", this.getReleaseVersion(), this.getPartNo(), this.getMarketName2())); + } + + if (Strings.isNullOrEmpty(this.getType())) { + this.setType("system"); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private void dispatchUpdaterScript(InputStream is) { + try { + String script = IOUtils.toString(is, "UTF-8"); + String key = "ro.build.date.utc"; + String buildDate = this.lastSubString(script, key, "(", ","); + this.setOtaProperty(key, buildDate); + key = "ro.product.device"; + String value = this.subString(script, key, "\"", "\""); + if (!Strings.isNullOrEmpty(value)) { + this.setOtaProperty(key, value); + } + + key = "ro.mitac.product"; + value = this.subString(script, key, "\"", "\""); + if (!Strings.isNullOrEmpty(value)) { + this.setOtaProperty(key, value); + } + + key = "ro.mitac.sku"; + value = this.subString(script, key, "\"", "\""); + if (!Strings.isNullOrEmpty(value)) { + this.setOtaProperty(key, value); + } + + if (Strings.isNullOrEmpty(this.getDeviceId())) { + value = this.subString(script, "get_device_compatible", "\"", "\""); + if (!Strings.isNullOrEmpty(value)) { + this.setDeviceId(value); + } + } + + if (Strings.isNullOrEmpty(this.getBuildTags())) { + String fingerPrint = this.subString(script, "ui_print(\"Target", " ", "\""); + if (!Strings.isNullOrEmpty(fingerPrint)) { + String buildTags = fingerPrint.substring(fingerPrint.lastIndexOf(47) + 1); + if (!Strings.isNullOrEmpty(buildTags)) { + this.setBuildTags(buildTags); + } + } + } + } catch (IOException var8) { + } + + } + + private void dispatchProp(InputStream input) { + try { + Properties properties = new Properties(); + properties.load(input); + + for(Map.Entry entry : properties.entrySet()) { + this.setOtaProperty((String)entry.getKey(), (String)entry.getValue()); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private void dispatchJson(InputStream input) { + if (input != null) { + JsonElement json = McJsonUtils.toJsonElement(input); + if (json != null && json.isJsonObject()) { + JsonObject jProps = json.getAsJsonObject(); + + for(Map.Entry entry : jProps.entrySet()) { + String key = (String)entry.getKey(); + JsonElement value = (JsonElement)entry.getValue(); + if (value.isJsonPrimitive()) { + this.setOtaProperty(key, value.getAsString()); + } + } + } + + } + } + + private void dispatchOtaCert(InputStream otaCertIs) { + McOtaCert otaCert = new McOtaCert(otaCertIs); + this.setOtaCertHash(otaCert.getBase64Hash()); + } + + private void setOtaProperty(String key, String value) { + switch (key) { + case "ota-type": + this.setAbUpdate(value.equals("AB")); + break; + case "persist.sys.rgimg.brand": + if (Strings.isNullOrEmpty(this.getBrand())) { + this.setBrand(value); + } + break; + case "ro.build.date.utc": + case "post-timestamp": + case "persist.sys.rgimg.build_utc": + if (this.getBuildDate() < 0L) { + this.setBuildDate(Long.valueOf(value)); + } + break; + case "persist.sys.rgimg.customer": + if (Strings.isNullOrEmpty(this.getCustomer())) { + this.setCustomer(value); + } + break; + case "persist.sys.rgimg.customer_id": + if (Strings.isNullOrEmpty(this.getCustomerId())) { + this.setCustomerId(value); + } + break; + case "persist.sys.rgimg.mkt_name1": + if (Strings.isNullOrEmpty(this.getMarketName1())) { + this.setMarketName1(value); + } + break; + case "persist.sys.rgimg.mkt_name2": + if (Strings.isNullOrEmpty(this.getMarketName2())) { + this.setMarketName2(value); + } + break; + case "persist.sys.rgimg.part_num": + if (Strings.isNullOrEmpty(this.getPartNo())) { + this.setPartNo(value); + } + break; + case "product-code": + case "ro.mitac.product": + case "persist.sys.rgimg.product": + if (Strings.isNullOrEmpty(this.getProductId())) { + this.setProductId(value); + } + break; + case "persist.sys.rgimg.release_ver": + if (Strings.isNullOrEmpty(this.getReleaseVersion())) { + this.setReleaseVersion(value); + } + break; + case "persist.sys.rgimg.script_ver": + if (Strings.isNullOrEmpty(this.getScriptVersion())) { + this.setScriptVersion(value); + } + break; + case "persist.sys.rgimg.target_device": + case "pre-device": + if (Strings.isNullOrEmpty(this.getDeviceId())) { + this.setDeviceId(value); + } + break; + case "persist.sys.rgimg.target_product": + if (Strings.isNullOrEmpty(this.getTargetProduct())) { + this.setTargetProduct(value); + } + break; + case "mitac-display-id": + String curDisplayId = this.getDisplayId(); + this.setProductDisplayId(value); + if (Strings.isNullOrEmpty(curDisplayId)) { + this.setDisplayId(value); + } + + if (Strings.isNullOrEmpty(this.getSkuId())) { + String skuId = parseSkuId(value); + if (!Strings.isNullOrEmpty(skuId)) { + this.setSkuId(skuId); + } + } + break; + case "display-id": + case "ro.build.display.id": + String curDisplayId = this.getDisplayId(); + if (Strings.isNullOrEmpty(curDisplayId) || !curDisplayId.equals(value)) { + this.setDisplayId(value); + } + + if (Strings.isNullOrEmpty(this.getSkuId())) { + String skuId = parseSkuId(value); + if (!Strings.isNullOrEmpty(skuId)) { + this.setSkuId(skuId); + } + } + break; + case "pre-display-id": + this.setPreDisplayId(value); + break; + case "mitac-package-type": + this.setType(value); + case "post-build-incremental": + default: + break; + case "post-sdk-level": + if (this.getSdkLevel() < 0) { + this.setSdkLevel(Integer.valueOf(value)); + } + break; + case "post-security-patch-level": + if (Strings.isNullOrEmpty(this.getSecurityPatchLevel())) { + this.setSecurityPatchLevel(value); + } + break; + case "pre-build": + this.setPreBuild(value); + break; + case "post-build": + this.dispatchPostBuild(value); + break; + case "sku-id": + case "ro.mitac.sku": + this.setSkuId(value); + break; + case "base-sku-compatibility": + if (!this.hasCompatibleSkuIds()) { + this.setCompatibleSkuIds(value); + } + break; + case "ro.build.tags": + if (Strings.isNullOrEmpty(this.getBuildTags())) { + this.setBuildTags(value); + } + break; + case "modem-firmware-sku": + if (Strings.isNullOrEmpty(this.getModemSku())) { + this.setModemSku(value); + } + break; + case "modem-firmware-version": + if (Strings.isNullOrEmpty(this.getModemFirmwareVersion())) { + this.setModemFirmwareVersion(value); + } + break; + case "modem-firmware-long-version": + if (Strings.isNullOrEmpty(this.getModemFirmwareLongVersion())) { + this.setModemFirmwareLongVersion(value); + } + } + + } + + public String getPostBuild() { + return this.getOtaInfo().getString("postBuild"); + } + + private void dispatchPostBuild(String text) { + this.setOtaInfo("postBuild", text); + String[] tags = text.split(":"); + if (tags.length >= 3) { + String[] tokens = tags[1].split("/"); + if (Strings.isNullOrEmpty(this.getOsVersion())) { + this.setOsVersion(tokens[0]); + } + + tokens = tags[2].split("/"); + if (Strings.isNullOrEmpty(this.getBuildType())) { + this.setBuildType(tokens[0]); + } + + if (Strings.isNullOrEmpty(this.getBuildTags())) { + this.setBuildTags(tokens[1]); + } + } + + } + + private String subString(String sb, String key, String prefix, String suffix) { + int keyIndex = sb.indexOf(key); + if (keyIndex < 0) { + return null; + } else { + int startIndex = sb.indexOf(prefix, keyIndex + key.length() + 1) + 1; + int endIndex = sb.indexOf(suffix, startIndex + 1); + return startIndex < endIndex ? sb.substring(startIndex, endIndex) : ""; + } + } + + private String lastSubString(String sb, String key, String prefix, String suffix) { + int keyIndex = sb.indexOf(key); + int endIndex = sb.lastIndexOf(",", keyIndex); + int startIndex = sb.lastIndexOf("(", endIndex) + 1; + return startIndex < endIndex ? sb.substring(startIndex, endIndex) : ""; + } + + public int compareTo(OtaFile other) { + int result = this.getSkuId().compareTo(other.getSkuId()); + if (result == 0) { + boolean isThisSystemImage = this.isSystemImage(); + boolean isOtherSystemImage = other.isSystemImage(); + if (isThisSystemImage != isOtherSystemImage) { + if (isThisSystemImage) { + return -1; + } + + return 1; + } + + result = (int)(this.getBuildDate() - other.getBuildDate()); + if (result == 0) { + if (this.isPartial() && !other.isPartial()) { + return -1; + } + + if (!this.isPartial() && other.isPartial()) { + return 1; + } + } + } + + return result; + } +} diff --git a/src/main/java/com/midm/model/file/REPORT_ERROR.java b/src/main/java/com/midm/model/file/REPORT_ERROR.java new file mode 100644 index 0000000..475cb32 --- /dev/null +++ b/src/main/java/com/midm/model/file/REPORT_ERROR.java @@ -0,0 +1,37 @@ +package com.midm.model.file; + +import java.util.List; + +public enum REPORT_ERROR { + UNKNOWN(1000), + FILE_ERROR(1001), + UNHANDLED_HTTP_CODE(1002), + HTTP_DATA_ERROR(1004), + TOO_MANY_REDIRECTS(1005), + INSUFFICIENT_SPACE(1006), + DEVICE_NOT_FOUND(1007), + CANNOT_RESUME(1008), + FILE_ALREADY_EXISTS(1009), + FILE_MISMATCHED(2001); + + public static final List COLLECT_SSN = List.of(UNKNOWN, FILE_ERROR, INSUFFICIENT_SPACE, DEVICE_NOT_FOUND, CANNOT_RESUME, FILE_ALREADY_EXISTS); + private int value; + + private REPORT_ERROR(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public static REPORT_ERROR fromValue(int value) { + for(REPORT_ERROR e : values()) { + if (e.getValue() == value) { + return e; + } + } + + return null; + } +} diff --git a/src/main/java/com/midm/model/log/MidmLog.java b/src/main/java/com/midm/model/log/MidmLog.java new file mode 100644 index 0000000..6b04888 --- /dev/null +++ b/src/main/java/com/midm/model/log/MidmLog.java @@ -0,0 +1,142 @@ +package com.midm.model.log; + +import com.google.common.base.Strings; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.internet.http.UserAgent; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.index.CompoundIndexes; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@CompoundIndexes({@CompoundIndex( + def = "{'category':1, 'loggedAt':1}" +), @CompoundIndex( + def = "{'forWhat':1, 'loggedAt': -1}" +), @CompoundIndex( + def = "{'forWhat':1, 'log': 1}" +)}) +public class MidmLog { + @Id + private UUID uuid; + private UUID forWhat; + private String category; + private String log; + private DbObject reference; + private Date loggedAt; + @DBRef + private User logger; + + public MidmLog() { + this.setUuid(UUID.randomUUID()); + this.setLoggedAt(new Date()); + } + + public MidmLog(User user, UUID forWhat, String category, String log) { + this(); + if (user != null) { + this.setLogger(user); + } + + this.setForWhat(forWhat); + this.setCategory(category); + this.setLog(log); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public UUID getForWhat() { + return this.forWhat; + } + + public void setForWhat(UUID forWhat) { + this.forWhat = forWhat; + } + + public String getCategory() { + return this.category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getLog() { + return this.log; + } + + public void setLog(String log) { + this.log = log; + } + + public DbObject getReference() { + if (this.reference == null) { + this.reference = new DbObject(); + } + + return this.reference; + } + + public boolean hasReference() { + return this.reference != null && this.reference.size() > 0; + } + + public void setReference(DbObject reference) { + this.reference = reference; + } + + public void setReference(UserAgent agent, String sessionId, String remoteIp) { + if (agent != null) { + this.addReference("browser", agent.agentFamily()); + this.addReference("os", agent.osFamily()); + this.addReference("device", agent.deviceFamily()); + } + + if (!Strings.isNullOrEmpty(sessionId)) { + this.addReference("sessionId", sessionId); + } + + if (!Strings.isNullOrEmpty(remoteIp)) { + this.addReference("remoteIp", remoteIp); + } + + } + + public void addReference(String key, Object value) { + this.getReference().put(key, value); + } + + public UUID getLoggerUuid() { + return this.logger != null ? this.logger.getUuid() : null; + } + + public Date getLoggedAt() { + return this.loggedAt; + } + + public void setLoggedAt(Date loggedAt) { + this.loggedAt = loggedAt; + } + + public void setLoggedAt(long loggedAt) { + this.loggedAt = new Date(loggedAt); + } + + public User getLogger() { + return this.logger; + } + + public void setLogger(User logger) { + this.logger = logger; + } +} diff --git a/src/main/java/com/midm/model/message/MIDM_REQUEST.java b/src/main/java/com/midm/model/message/MIDM_REQUEST.java new file mode 100644 index 0000000..8ba124c --- /dev/null +++ b/src/main/java/com/midm/model/message/MIDM_REQUEST.java @@ -0,0 +1,59 @@ +package com.midm.model.message; + +public enum MIDM_REQUEST { + PING(99, "ping"), + CONNECT(100, "connect"), + DISCONNECT(101, "disconnect"), + CHECKIN(102, "checkin"), + CHECKOUT(103, "checkout"), + ENROLL(104, "enroll"), + DEVICE_INFO(105, "update_device_info"), + CLIENT_UPDATE(121, "client_update"), + UPDATE_PROFILE(131, "profile_update"), + UPDATE_ALL_PROFILES(132, "profile_update_all"), + REMOVE_PROFILE(136, "profile_remove"), + COMMAND(200, "command"), + QUERY(210, "query"), + EXEC(220, "exec"), + DEVICE_STATE(300, "device_state"), + USER_LOG(301, "userLog"), + DEVICE_LOG(302, "deviceLog"), + RTC(400, "rtc"), + UNKNOWN(-1, ""); + + private int code; + private String request; + + private MIDM_REQUEST(int code, String request) { + this.code = code; + this.request = request; + } + + public int getCode() { + return this.code; + } + + public String getRequest() { + return this.request; + } + + public static MIDM_REQUEST get(int code) { + for(MIDM_REQUEST request : values()) { + if (request.code == code) { + return request; + } + } + + return UNKNOWN; + } + + public static MIDM_REQUEST get(String requestText) { + for(MIDM_REQUEST request : values()) { + if (request.getRequest().equalsIgnoreCase(requestText.trim())) { + return request; + } + } + + return UNKNOWN; + } +} diff --git a/src/main/java/com/midm/model/message/MidmPacket.java b/src/main/java/com/midm/model/message/MidmPacket.java new file mode 100644 index 0000000..b462ef1 --- /dev/null +++ b/src/main/java/com/midm/model/message/MidmPacket.java @@ -0,0 +1,135 @@ +package com.midm.model.message; + +import com.google.common.base.Charsets; +import com.mitac.cell.data.McCompress; +import com.mitac.cell.data.McDecompress; +import com.mitac.cell.utils.McJsonUtils; +import java.io.Serializable; +import java.nio.ByteBuffer; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.web.socket.BinaryMessage; +import org.springframework.web.socket.TextMessage; + +@Document +public class MidmPacket implements Serializable { + @Id + private UUID uuid; + private UUID recieverUuid; + private UUID queryUuid; + @Transient + private MidmQuery query; + private MidmResponse feedback; + private Date readAt; + + public MidmPacket() { + this.setUuid(UUID.randomUUID()); + } + + public MidmPacket(int code) { + this.init(); + this.setQuery(new MidmQuery(code)); + } + + public MidmPacket(MIDM_REQUEST request) { + this(request.getCode()); + } + + private void init() { + this.setUuid(UUID.randomUUID()); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public UUID getRecieverUuid() { + return this.recieverUuid; + } + + public void setRecieverUuid(UUID recieverUuid) { + this.recieverUuid = recieverUuid; + } + + public UUID getQueryUuid() { + return this.queryUuid; + } + + public void setQueryUuid(UUID queryUuid) { + this.queryUuid = queryUuid; + } + + public MidmQuery getQuery() { + return this.query; + } + + public void setQuery(MidmQuery query) { + this.query = query; + } + + public Object getParam(String key) { + return this.getQuery().getParam(key); + } + + public void setParam(String key, Object value) { + this.getQuery().setParam(key, value); + } + + public MidmResponse getFeedback() { + return this.feedback; + } + + public void setFeedback(MidmResponse feedback) { + this.feedback = feedback; + } + + public void setFeedback(int code, String message) { + this.feedback = new MidmResponse(code, message); + } + + public void setFeedback(int code, String message, Object data) { + this.feedback = new MidmResponse(code, message, data); + } + + public Date getReadAt() { + return this.readAt; + } + + public void setReadAt(Date readAt) { + this.readAt = readAt; + } + + public TextMessage toMessage() { + return new TextMessage(this.toString()); + } + + public BinaryMessage toBinary() { + byte[] bytes = McCompress.compress(this.toString()); + return new BinaryMessage(bytes); + } + + public String toString() { + return McJsonUtils.toJson(this); + } + + public static MidmPacket toPacket(TextMessage message) { + return (MidmPacket)McJsonUtils.toObject((String)message.getPayload(), MidmPacket.class); + } + + public static MidmPacket topacket(BinaryMessage message) { + ByteBuffer bytes = (ByteBuffer)message.getPayload(); + byte[] decompressed = McDecompress.decompress(bytes.array()); + return (MidmPacket)McJsonUtils.toObject(new String(decompressed, Charsets.UTF_8), MidmPacket.class); + } + + public static MidmPacket toPacket(String message) { + return (MidmPacket)McJsonUtils.toObject(message, MidmPacket.class); + } +} diff --git a/src/main/java/com/midm/model/message/MidmQuery.java b/src/main/java/com/midm/model/message/MidmQuery.java new file mode 100644 index 0000000..db7671b --- /dev/null +++ b/src/main/java/com/midm/model/message/MidmQuery.java @@ -0,0 +1,113 @@ +package com.midm.model.message; + +import com.mitac.cell.db.DbObject; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class MidmQuery { + private UUID uuid; + private UUID senderUuid; + private int code; + private DbObject query; + private boolean isInstant; + private Date registeredAt; + + public MidmQuery() { + this.init(); + } + + public MidmQuery(int code) { + this(); + this.setCode(code); + } + + public void init() { + this.setUuid(UUID.randomUUID()); + this.isInstant = true; + this.setRegisteredAt(new Date()); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public UUID getSenderUuid() { + return this.senderUuid; + } + + public void setSenderUuid(UUID senderUuid) { + this.senderUuid = senderUuid; + } + + public int getCode() { + return this.code; + } + + public void setCode(int code) { + this.code = code; + } + + public DbObject getQuery() { + if (this.query == null) { + this.query = new DbObject(); + } + + return this.query; + } + + public void setQuery(DbObject query) { + this.query = query; + } + + public String getRequest() { + return (String)this.getQuery().get("request"); + } + + public void setRequest(String request) { + this.getQuery().put("request", request); + } + + public DbObject getParams() { + DbObject params = this.getQuery().getDbObject(new String[]{"params"}); + if (params == null) { + params = new DbObject(); + this.getQuery().put("params", params); + } + + return params; + } + + public Object getParam(String key) { + return this.getParams().get(key); + } + + public String getCommand() { + return this.getParam("command").toString(); + } + + public void setParam(String key, Object value) { + this.getParams().put(key, value); + } + + public boolean isInstant() { + return this.isInstant; + } + + public void setInstant(boolean isInstant) { + this.isInstant = isInstant; + } + + public Date getRegisteredAt() { + return this.registeredAt; + } + + public void setRegisteredAt(Date registeredAt) { + this.registeredAt = registeredAt; + } +} diff --git a/src/main/java/com/midm/model/message/MidmResponse.java b/src/main/java/com/midm/model/message/MidmResponse.java new file mode 100644 index 0000000..ad8c5eb --- /dev/null +++ b/src/main/java/com/midm/model/message/MidmResponse.java @@ -0,0 +1,268 @@ +package com.midm.model.message; + +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McJsonUtils; +import com.mongodb.client.result.UpdateResult; +import java.util.List; +import java.util.Map; +import org.springframework.data.domain.Page; +import org.springframework.web.socket.TextMessage; + +public class MidmResponse { + public static final String MESSAGE_SUCCEED = "succeed"; + public static final String MESSAGE_FAILED = "failed"; + public static final int CODE_SERVICE_CONNECTED = 100; + public static final int CODE_SUCCEED = 200; + public static final int CODE_CHECKEDIN = 110; + public static final int CODE_ENROLLED = 111; + public static final int CODE_ENROLL_REJECTED = 112; + public static final int CODE_DEVICE_REGISTERD = 113; + public static final int CODE_DEVICE_UPDATED = 114; + public static final int CODE_LICENSE_EXPIRED = 115; + public static final int CODE_MESSAGE_NOTIFY = 116; + public static final int CODE_REPORT_READY = 117; + public static final int CODE_REPORT_GENERATE_FAIL = 118; + public static final int CODE_HOST_LICENSE_READY = 119; + public static final int CODE_SITE_LICENSE_READY = 109; + public static final int CODE_SITE_LICENSE_REQUESTED = 108; + public static final int CODE_SITE_UPGRADE_REQUESTED = 107; + public static final int CODE_SITE_UPGRADE_SUCCESS = 106; + public static final int CODE_UPDATE_CIENT_APPS = 121; + public static final int CODE_ONLINE_STATE_CHANGED = 211; + public static final int CODE_DEVICE_STATE_CHANGED = 300; + public static final int FEEDBACK_APP_LIST = 120; + public static final int FEEDBACK_APP_INSTALLED = 121; + public static final int FEEDBACK_APP_UNINSTALLED = 122; + public static final int FEEDBACK_APP_ENABLE = 123; + public static final int FEEDBACK_APP_DISABLE = 124; + public static final int FEEDBACK_APP_SHOW = 125; + public static final int FEEDBACK_APP_HIDE = 126; + public static final int FEEDBACK_APP_INFO = 127; + public static final int FEEDBACK_FILE_LIST = 130; + public static final int FEEDBACK_FILE_STORAGE = 131; + public static final int FEEDBACK_FILE_COPY = 132; + public static final int FEEDBACK_FILE_RENAME = 133; + public static final int FEEDBACK_FILE_MOVE = 134; + public static final int FEEDBACK_FILE_REMOVE = 135; + public static final int FEEDBACK_FILE_MKDIR = 136; + public static final int FEEDBACK_FILE_PUSH = 137; + public static final int FEEDBACK_FILE_PULL = 138; + public static final int FEEDBACK_FILE_LOGCAT = 139; + public static final int FEEDBACK_EXEC = 140; + public static final int FEEDBACK_EXEC_LOGCAT = 141; + public static final int FEEDBACK_HARDWARE_INFO = 170; + public static final int FEEDBACK_SOFTWARE_INFO = 180; + public static final int FEEDBACK_MEMORY_USAGE = 190; + public static final int FEEDBACK_BATTERY_INFO = 191; + public static final int FEEDBACK_DATA_USAGE = 192; + public static final int FEEDBACK_ACTIVE_NETWORK = 193; + public static final int FEEDBACK_NETWORK = 194; + public static final int FEEDBACK_LOCATION = 198; + public static final int FEEDBACK_SCREEN_CAPTURED = 199; + public static final int FEEDBACK_ONLINE_STATE = 211; + public static final int FEEDBACK_CAMERA_STATE = 212; + public static final int FEEDBACK_DEVICE_STATE = 300; + public static final int CODE_FAILED = 400; + public static final int CODE_NOT_FOUND = 404; + public static final int CODE_FAIL_USER_NOT_FOUND = 410; + public static final int CODE_FAIL_WRONG_PASSWROD = 411; + public static final int CODE_FAIL_USER_NOT_AVAILABLE = 412; + public static final int CODE_FAIL_INSUFFICIENT_INFO = 413; + public static final int CODE_FAIL_USER_LOGGED_IN = 414; + public static final int CODE_FAIL_NO_AUTH_INFO = 415; + public static final int CODE_FAIL_REGISTERED_TO_OTHER = 416; + public static final int CODE_FAIL_VERSION_DUPLICATE = 417; + public static final int CODE_FAIL_USER_NOT_AGREED = 418; + public static final int CODE_FAIL_SAME_NAME_NOT_ALLOW = 419; + public static final int CODE_FAIL_HOST_EXPIRED = 420; + public static final int CODE_FAIL_HOST_EXCEED_DEVICE_LIMIT = 421; + public static final int CODE_FAIL_INVALID = 422; + public static final int CODE_FAIL_EXISTING_USER = 423; + public static final int CODE_FAIL_EXCEED_LOGIN_FAILURE = 424; + public static final int CODE_FAIL_API_ONLY_USER = 425; + public static final int CODE_FAIL_SITE_NOT_FOUND = 450; + public static final int CODE_FAIL_NO_SITE_AVAILABLE = 451; + public static final int CODE_FAIL_SITE_NO_USER = 452; + public static final int CODE_FAIL_SITE_USER_DISABLED = 453; + public static final int CODE_FAIL_SITE_SAME = 455; + public static final int CODE_FAIL_DEVICE_NO_SERIAL = 461; + public static final int CODE_FAIL_DEVICE_NO_SITE = 462; + public static final int CODE_FAIL_NO_DEVICE_EXISTS = 463; + public static final int CODE_FAIL_DEVICE_NO_LICENSE = 464; + public static final int CODE_FAIL_CHILD_EXISTS = 466; + public static final int CODE_FAIL_DEVICE_EXISTS = 467; + public static final int CODE_FAIL_LICENSE_EXPIRED = 115; + public static final int CODE_ERROR_NO_RECORD = 421; + public static final int CODE_ERROR_TOKEN_NOT_DEFINED = 461; + public static final int CODE_ERROR_EXPIRED_TOKEN = 462; + public static final int CODE_ERROR_INVALID_TOKEN = 463; + public static final int CODE_ERROR_URL_FORMAT = 431; + public static final int CODE_ERROR_IO_EXEPTION = 432; + public static final int CODE_ERROR_NO_PERMISSION = 433; + public static final int CODE_ERROR_INVALID_SYSTEM_IMAGE = 441; + public static final int CODE_UNKOWN = -1; + public static final String MESSAGE_NOT_ALLOWED = "Not allowed."; + public static final String MESSAGE_NOT_AUTHORIZED = "Not authorized."; + public static final String MESSAGE_NO_PERMISSION = "No permission."; + public static final String MESSAGE_NO_USER_EXISTS = "No user exists."; + public static final String MESSAGE_NO_SITE_AVAILABLE = "No site available."; + public static final String MESSAGE_NO_DEVICE_EXISTS = "No device exists."; + public static final String MESSAGE_NO_SERIAL_DEFINED = "No serial no. defined."; + public static final String MESSAGE_DEVICE_EXISTS = "Existing device."; + public static final String MESSAGE_NO_GROUP_EXISTS = "No group exists."; + public static final String MESSAGE_NO_GROUP = "No group: "; + public static final String MESSAGE_NO_RECORDS = "No records."; + public static final String MESSAGE_NO_REPORTS = "No reports."; + public static final String MESSAGE_NO_LICENSE = "No license."; + public static final String MESSAGE_NO_LOCATIONS = "No locations."; + public static final String MESSAGE_NO_PROFILE_FOUND = "No profile found."; + public static final String MESSAGE_NO_APP_FOUND = "No apps found."; + public static final String MESSAGE_NO_USER_LOGGED_IN = "No user logged in."; + private int code; + private String message; + private Object data; + private Object reference; + private Integer totalPage; + private Long size; + private Long totalSize; + + public MidmResponse() { + } + + public MidmResponse(int code, String msg) { + this.setCode(code); + this.setMessage(msg); + } + + public MidmResponse(int code, String msg, Object data) { + this.setCode(code); + this.setMessage(msg); + this.setData(data); + } + + public int getCode() { + return this.code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Object getData() { + return this.data; + } + + public DbObject getDataAsDbObject() { + Object data = this.getData(); + return data == null ? new DbObject() : new DbObject((Map)data); + } + + public void setData(Object data) { + if (data instanceof UpdateResult) { + UpdateResult result = (UpdateResult)data; + this.data = (new DbObject("matched", result.getMatchedCount())).append("modified", result.getModifiedCount()); + } else { + this.data = data; + } + + } + + public Object getReference() { + return this.reference; + } + + public DbObject getRefereceAsDbObject() { + Object data = this.getReference(); + return data == null ? new DbObject() : new DbObject((Map)data); + } + + public void setReference(Object reference) { + this.reference = reference; + } + + public int getTotalPage() { + return this.totalPage; + } + + public void setTotalPages(int totalPage) { + this.totalPage = totalPage; + } + + public long getSize() { + return this.size; + } + + public void setSize(long size) { + this.size = size; + } + + public long getTotalSize() { + return this.totalSize; + } + + public void setTotalSize(long totalSize) { + this.totalSize = totalSize; + } + + public String toString() { + return McJsonUtils.toJson(this); + } + + public TextMessage toTextMessage() { + return new TextMessage(this.toString()); + } + + public static String getSucceedResponse() { + return getResponse(200, "succeed"); + } + + public static String getSucceedResponse(List list) { + MidmResponse response = new MidmResponse(200, "succeed"); + if (list != null) { + response.setData(list); + response.setSize((long)list.size()); + } + + return response.toString(); + } + + public static String getSucceedResponse(Page page) { + MidmResponse response = new MidmResponse(200, "succeed"); + if (page != null) { + response.setData(page.getContent()); + response.setTotalPages(page.getTotalPages()); + response.setSize((long)page.getNumberOfElements()); + response.setTotalSize(page.getTotalElements()); + } + + return response.toString(); + } + + public static String getSucceedResponse(Object data) { + return getResponse(200, "succeed", data); + } + + public static String getFailedResponse() { + return getResponse(400, "failed"); + } + + public static String getResponse(int code, String msg) { + return (new MidmResponse(code, msg)).toString(); + } + + public static String getResponse(int code, String msg, Object data) { + return (new MidmResponse(code, msg, data)).toString(); + } + + public static String getResponse(Object object) { + return McJsonUtils.toJson(object); + } +} diff --git a/src/main/java/com/midm/model/news/MessageLog.java b/src/main/java/com/midm/model/news/MessageLog.java new file mode 100644 index 0000000..002c0e0 --- /dev/null +++ b/src/main/java/com/midm/model/news/MessageLog.java @@ -0,0 +1,124 @@ +package com.midm.model.news; + +import com.midm.model.org.User; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class MessageLog { + @Id + private UUID uuid; + @DBRef + private NewsMessage message; + @DBRef + private User reader; + @Indexed + private UUID siteUuid; + @Indexed + private Date readDate; + @Indexed + private boolean isCheck; + @Indexed + private boolean isRead; + @Indexed + private Date checkDate; + @Indexed + private Date notified; + + public MessageLog() { + } + + public MessageLog(NewsMessage message, User reader, UUID siteUuid) { + this.uuid = UUID.randomUUID(); + this.message = message; + this.reader = reader; + this.siteUuid = siteUuid; + this.isCheck = false; + this.notified = new Date(); + } + + public MessageLog(NewsMessage message, UUID userUuid, UUID siteUuid) { + this.uuid = UUID.randomUUID(); + this.message = message; + this.reader = new User(userUuid); + this.siteUuid = siteUuid; + this.isCheck = false; + this.notified = new Date(); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public NewsMessage getMessage() { + return this.message; + } + + public void setMessage(NewsMessage message) { + this.message = message; + } + + public User getReader() { + return this.reader; + } + + public void setReader(User reader) { + this.reader = reader; + } + + public boolean isCheck() { + return this.isCheck; + } + + public void setCheck(boolean isCheck) { + this.isCheck = isCheck; + } + + public boolean isRead() { + return this.isRead; + } + + public void setRead(boolean isRead) { + this.isRead = isRead; + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public Date getNotified() { + return this.notified; + } + + public void setNotified(Date notified) { + this.notified = notified; + } + + public Date getReadDate() { + return this.readDate; + } + + public void setReadDate(Date readDate) { + this.readDate = readDate; + } + + public Date getCheckDate() { + return this.checkDate; + } + + public void setCheckDate(Date checkDate) { + this.checkDate = checkDate; + } +} diff --git a/src/main/java/com/midm/model/news/NewsMessage.java b/src/main/java/com/midm/model/news/NewsMessage.java new file mode 100644 index 0000000..4739123 --- /dev/null +++ b/src/main/java/com/midm/model/news/NewsMessage.java @@ -0,0 +1,306 @@ +package com.midm.model.news; + +import com.google.gson.internal.LinkedTreeMap; +import com.midm.model.device.Device; +import com.midm.model.message.MidmPacket; +import com.midm.model.message.MidmQuery; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McEmailUtils; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import org.joda.time.DateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class NewsMessage { + @Id + private UUID uuid; + @DBRef + private User writer; + private String category; + private String forWhat; + private DbObject reference; + private DbObject message; + private Boolean isUnremovable; + private Boolean isEnabled; + private Date sendSchedule; + private Date expiry; + @Transient + private boolean sendNow; + private Date created; + private Date updated; + + public NewsMessage(Device device, String category) { + this.init(); + this.category = "device_" + category; + this.reference.put("uuid", device.getUuid()); + } + + public NewsMessage(Device device) { + this.init(); + this.reference.put("uuid", device.getUuid()); + } + + public NewsMessage(MidmPacket packet) { + MidmQuery query = packet.getQuery(); + this.setUuid(query.getUuid()); + this.created = query.getRegisteredAt(); + this.updated = this.created; + String request = query.getRequest(); + String command = query.getCommand(); + this.category = String.format("%s_%s", request, command); + this.getReference().put("userUuid", query.getSenderUuid()); + this.getReference().put("deviceUuid", packet.getRecieverUuid()); + this.getReference().put("query", query.getQuery()); + } + + public NewsMessage() { + this.init(); + } + + public void init() { + this.uuid = UUID.randomUUID(); + this.created = new Date(); + this.updated = this.created; + } + + public DbObject getMessage() { + if (this.message == null) { + this.message = new DbObject(); + } + + return this.message; + } + + public DbObject getMessage(Locale locale) { + return this.getMessage(locale.toLanguageTag()); + } + + public DbObject getMessage(String languageTag) { + DbObject message = this.getMessage(); + DbObject localedMessage = new DbObject(); + if (message.get(languageTag) == null) { + message.put(languageTag, localedMessage); + } else if (message.get(languageTag) instanceof LinkedTreeMap) { + for(Map.Entry entry : ((LinkedTreeMap)message.get(languageTag)).entrySet()) { + localedMessage.append((String)entry.getKey(), entry.getValue()); + } + + message.put(languageTag, localedMessage); + } else if (message.get(languageTag) instanceof DbObject) { + localedMessage = (DbObject)message.get(languageTag); + message.put(languageTag, localedMessage); + } else if (message.get(languageTag) instanceof org.bson.Document) { + for(Map.Entry entry : ((org.bson.Document)message.get(languageTag)).entrySet()) { + localedMessage.append((String)entry.getKey(), entry.getValue()); + } + + message.put(languageTag, localedMessage); + } + + return localedMessage; + } + + public void setMessage(DbObject message) { + this.message = message; + } + + public void setMessage(String title, String content) { + this.setTitle(title); + this.setContent(content); + } + + public String getTitle() { + return this.getMessage("en-US").getString("title"); + } + + public String getSummary() { + return this.getMessage().getString("summary"); + } + + public boolean hasContent() { + return this.getMessage().containsKey("content"); + } + + public String getContent() { + return this.getMessage("en-US").getString("content"); + } + + public String getTitle(String locale) { + return this.getMessage(locale).getString("title"); + } + + public String getSummary(String locale) { + return this.getMessage(locale).getString("summary"); + } + + public boolean hasContent(String locale) { + return this.getMessage(locale).containsKey("content"); + } + + public String getContent(String locale) { + return this.getMessage(locale).getString("content"); + } + + public List getMailsTo() { + return McEmailUtils.parseMails(this.getMessage().getString("to")); + } + + public void setMessage(String title, String content, String summary) { + this.setMessage(Locale.US.toLanguageTag(), title, content, summary); + } + + public void setMessage(String languageTag, String title, String content, String summary) { + this.setTitle(languageTag, title); + this.setContent(languageTag, content); + this.setSummary(languageTag, summary); + } + + public void setTitle(String title) { + this.setTitle(Locale.US.toLanguageTag(), title); + } + + public void setContent(String content) { + this.setContent(Locale.US.toLanguageTag(), content); + } + + public void setSummary(String summary) { + this.setSummary(Locale.US.toLanguageTag(), summary); + } + + public void setTitle(String languageTag, String title) { + DbObject message = this.getMessage(languageTag); + message.put("title", title); + } + + public void setContent(String languageTag, String content) { + DbObject message = this.getMessage(languageTag); + message.put("content", content); + } + + public DbObject getReference() { + if (this.reference == null) { + this.reference = new DbObject(); + } + + return this.reference; + } + + public void setReference(DbObject reference) { + this.reference = reference; + } + + public void setSummary(String languageTag, String summary) { + DbObject message = this.getMessage(languageTag); + message.put("summary", summary); + } + + public Boolean isUnremovable() { + return this.isUnremovable; + } + + public void setIsUnremovable(Boolean isUnremovable) { + this.isUnremovable = isUnremovable; + } + + public String getForWhat() { + return this.forWhat; + } + + public void setForWhat(String forWhat) { + this.forWhat = forWhat; + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public User getWriter() { + return this.writer; + } + + public void setWriter(User writer) { + this.writer = writer; + } + + public String getCategory() { + return this.category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Date getSendSchedule() { + return this.sendSchedule; + } + + public void setSendSchedule(Date sendSchedule) { + this.sendSchedule = sendSchedule; + } + + public boolean sendNow() { + return this.sendNow || this.sendSchedule == null || McDateTimeUtils.isSameDate(new DateTime(this.sendSchedule), DateTime.now()); + } + + public Date getExpiry() { + return this.expiry; + } + + public void setExpiry(Date expiry) { + this.expiry = expiry; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getUpdated() { + return this.updated; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } + + public Boolean getIsUnremovable() { + return this.isUnremovable; + } + + public Boolean isEnabled() { + return this.isEnabled; + } + + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } + + public boolean isSendNow() { + return this.sendNow; + } + + public void setSendNow(boolean sendNow) { + this.sendNow = sendNow; + } + + public String toDateString(String dateString, String format) { + DateTime dateTime = new DateTime(dateString); + return McDateTimeUtils.toString(dateTime, format); + } +} diff --git a/src/main/java/com/midm/model/org/Site.java b/src/main/java/com/midm/model/org/Site.java new file mode 100644 index 0000000..219b352 --- /dev/null +++ b/src/main/java/com/midm/model/org/Site.java @@ -0,0 +1,383 @@ +package com.midm.model.org; + +import com.google.common.base.Strings; +import com.midm.model.GeneralProfile; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McUuidUtils; +import java.util.Date; +import java.util.Set; +import java.util.TimeZone; +import java.util.UUID; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class Site extends GeneralProfile { + public static final String MODEL_MIDM = "midm"; + public static final String MODEL_MUST = "must"; + @DBRef + private Site reseller; + @Indexed( + unique = true + ) + private String idName; + @Transient + private Date latestVisit; + @Transient + private DbObject report; + + public Site() { + this.setEnabled(false); + } + + public Site(String model) { + this(); + this.setModel(model); + } + + public void init() { + this.setUuid(UUID.randomUUID()); + DbObject notiSettings = new DbObject("sendEmail", true); + DbObject notiRoles = new DbObject("enabled", true); + notiRoles.append("roles", new DbObject("SUPERVISOR", true)); + DbObject supportSettings = new DbObject("general", notiRoles); + supportSettings.append("maintenance", notiRoles).append("urgent", notiRoles); + notiSettings.append("support", supportSettings); + this.setSetting("noti", notiSettings); + this.setCreated(new Date()); + } + + public Site getReseller() { + return this.reseller; + } + + public void setReseller(Site reseller) { + this.reseller = reseller; + } + + public boolean isChild() { + return this.reseller != null; + } + + public boolean canCustomize() { + return true; + } + + public Object getDomainName() { + return this.getSetting("domainName"); + } + + public String getIdName() { + return this.idName; + } + + public void setIdName(String idName) { + this.idName = idName; + } + + public String getTitle() { + String siteName = (String)this.getSetting("theme", "siteName"); + return Strings.isNullOrEmpty(siteName) ? this.getName() : siteName; + } + + public boolean hasLogo() { + return this.getSettingAsBoolean("theme", "logo", false); + } + + public DbObject getPlan() { + return this.getProfileCategory(new String[]{"plan"}); + } + + public String getPlanName() { + DbObject plan = this.getPlan(); + return plan.getString("plan", "standard"); + } + + public String getShowPlanName() { + String planName = this.getPlanName(); + return this.getShowPlanName(planName); + } + + public String getShowPlanName(String planName) { + String name = ""; + if (planName.equals("lite")) { + name = "Lite"; + } else if (planName.equals("standard")) { + name = "Standard"; + } else if (planName.equals("standardWithBatteryPro")) { + name = "Std + Batt Pro"; + } + + return name; + } + + public void setPlan(DbObject plan) { + this.setProfile("plan", plan); + } + + public void setPlan(String plan) { + if (!Strings.isNullOrEmpty(plan)) { + this.setProfile("plan", "plan", plan); + DbObject profilePlan = this.getProfile().getDbObject(new String[]{"plan"}); + if (plan.equals("standard")) { + profilePlan.remove("features"); + } + + profilePlan.remove("upgradeStatus"); + } + } + + public String getUpgradeStatus() { + DbObject plan = this.getPlan(); + return plan.getString("upgradeStatus"); + } + + public boolean isUpgradeRequested() { + return "processing".equals(this.getUpgradeStatus()); + } + + public String getUpgradeTargetPlan() { + DbObject plan = this.getPlan(); + return plan.getString("targetPlan"); + } + + public String getModel() { + return (String)this.getProfile("model", "midm"); + } + + public void setModel(String model) { + this.setProfile("model", model); + } + + public String getPhone() { + return (String)this.getProfile("phone"); + } + + public String getAddress() { + return (String)this.getProfile("address"); + } + + public String getCountry() { + return (String)this.getProfile("country"); + } + + public boolean isReseller() { + return (Boolean)this.getProfile("isReseller", false); + } + + public void setIsReseller(boolean isReseller) { + this.setProfile("isReseller", isReseller); + } + + public boolean limitRegisteredDeviceOnly() { + return this.getSettingAsBoolean("enrollment", "registeredOnly", false); + } + + public Date getLatestVisit() { + return this.latestVisit; + } + + public void setLatestVisit(Date latestVisit) { + this.latestVisit = latestVisit; + } + + public DbObject getCredential() { + return this.getSettings().getDbObject(new String[]{"credential"}); + } + + public boolean isCredentialMatched(String credential) { + if (Strings.isNullOrEmpty(credential)) { + return false; + } else { + DbObject credentialSettings = this.getCredential(); + if (credentialSettings != null && !credentialSettings.isEmpty()) { + String siteCredential = credentialSettings.getString("credential"); + long cridentialExpiry = credentialSettings.getLong("expiry"); + return (cridentialExpiry == -1L || cridentialExpiry > (new Date()).getTime()) && credential.equals(siteCredential); + } else { + return false; + } + } + } + + public void setCredential(String credential) { + if (!Strings.isNullOrEmpty(credential)) { + DbObject value = new DbObject("credential", credential); + value.append("expiry", -1); + this.setSetting("credential", value); + } else { + this.getSettings().remove("credential"); + } + + } + + public void renewCredential() { + String credential = McUuidUtils.toBase64String(UUID.randomUUID(), true); + this.setCredential(credential); + } + + public DbObject getSettings() { + DbObject settings = super.getSettings(); + if (settings.get("theme") == null) { + DbObject themeSettings = new DbObject(); + themeSettings.put("skinColor", "steelblue"); + themeSettings.put("logo", false); + settings.put("theme", themeSettings); + } + + return settings; + } + + public DbObject getReport() { + if (this.report == null) { + this.report = new DbObject(); + } + + return this.report; + } + + public void setReport(DbObject report) { + this.report = report; + } + + public void addReport(String key, Object value) { + this.getReport().put(key, value); + } + + public boolean equals(Object obj) { + if (obj.hashCode() == this.hashCode()) { + return true; + } else if (obj instanceof Site) { + Site site = (Site)obj; + return this.getUuid().equals(site.getUuid()); + } else if (obj instanceof SiteInfo) { + SiteInfo siteInfo = (SiteInfo)obj; + return this.getUuid().equals(siteInfo.getSiteUuid()); + } else { + return obj instanceof UUID ? this.getUuid().equals((UUID)obj) : false; + } + } + + public boolean isLite() { + return this.getPlanName().equals("lite"); + } + + public boolean isStandard() { + return this.getPlanName().equals("standard"); + } + + public boolean isStandardWithBatteryPro() { + return this.getPlanName().equals("standardWithBatteryPro"); + } + + public boolean isMust() { + return this.getModel().equals("must"); + } + + public void setMust(boolean isMust) { + this.setModel("must"); + } + + public boolean isFeatureAllowed(String subCategory, String item) { + return !this.isLite() ? true : this.getProfileAsBoolean("plan", "features", subCategory, item, false); + } + + public DbObject getNotificationSettings() { + return this.getSettingsCategory(new String[]{"noti"}); + } + + public boolean notifyViaMail() { + return this.getNotificationSettings().getBoolean("sendEmail", false); + } + + public void setNotifyViaMail(boolean viaMail) { + this.getNotificationSettings().put("sendEmail", viaMail); + } + + public boolean notifyDeviceErrorMail() { + return this.getNotificationSettings().getBoolean("sendDeviceErrorEmail", false); + } + + public void setNotifyDeviceErrorMail(boolean enable) { + this.getNotificationSettings().put("sendDeviceErrorEmail", enable); + } + + public boolean notifyBatteryConditionMail() { + return this.getNotificationSettings().getBoolean("sendBatteryConditionEmail", false); + } + + public void setNotifyBatteryConditionMail(boolean enable) { + this.getNotificationSettings().put("sendBatteryConditionEmail", enable); + } + + public void setNotificationSettings(String category, String forWhat, boolean isEnabled) { + this.setNotificationSettings(category, forWhat, isEnabled, (Set)null); + } + + public void setNotificationSettings(String category, String forWhat, boolean isEnabled, Set roles) { + DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); + settings.put("isEnabled", isEnabled); + if (roles == null) { + settings.remove("roles"); + } else { + settings.put("roles", roles); + } + + } + + public void setNotificationSettings(String category, String forWhat, String key, String value) { + DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); + settings.put(key, value); + } + + public String getDataUsage() { + return this.getSettingsCategory(new String[]{"report"}).getString("dataUsage", "none"); + } + + public boolean collectDataUsage() { + return !this.getDataUsage().equals("none"); + } + + public Set getMessageRoles(String category, String forWhat) { + DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); + if (settings.getBoolean("enabled")) { + Object value = settings.get("roles"); + if (value instanceof Set) { + return (Set)value; + } else { + DbObject dt = (DbObject)value; + return dt.keySet(); + } + } else { + return null; + } + } + + public boolean hasTimeZone() { + return this.getSetting("general", "timeZone") != null; + } + + public void setTimeZone(TimeZone timeZone) { + this.setSetting("general", "timeZone", timeZone.getID()); + } + + public TimeZone getTimeZone() { + Object timeZone = this.getSetting("general", "timeZone"); + return timeZone != null ? TimeZone.getTimeZone((String)timeZone) : TimeZone.getDefault(); + } + + public String[] getIncludeApps() { + String installApps = this.getSettingsCategory(new String[]{"report"}).getString("installApps"); + return Strings.isNullOrEmpty(installApps) ? null : installApps.split("[,;\\s]+"); + } + + public DbObject getCallbackSetting() { + return this.getSettingsCategory(new String[]{"callback"}); + } + + public String toString() { + return String.format("%s(%s):%s", this.getName(), this.getIdName(), this.getUuid()); + } +} diff --git a/src/main/java/com/midm/model/org/SiteFile.java b/src/main/java/com/midm/model/org/SiteFile.java new file mode 100644 index 0000000..d864d4f --- /dev/null +++ b/src/main/java/com/midm/model/org/SiteFile.java @@ -0,0 +1,76 @@ +package com.midm.model.org; + +import com.midm.model.file.BaseFile; +import com.mitac.cell.io.McFile; +import java.util.Date; +import java.util.UUID; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class SiteFile extends BaseFile { + private String category; + private String forWhat; + private Date requested; + private Date expiry; + private String siteName; + @DBRef + private User requestedFrom; + + public SiteFile() { + } + + public SiteFile(User requestedFrom, UUID fileUuid, McFile file) { + this.setUserUuid(requestedFrom); + this.setFileUuid(fileUuid); + this.setFileInfo(file); + } + + public String getCategory() { + return this.category; + } + + public void setCategory(String category) { + this.category = category; + } + + public User getRequestedFrom() { + return this.requestedFrom; + } + + public void setRequestedFrom(User requestedFrom) { + this.requestedFrom = requestedFrom; + } + + public Date getRequested() { + return this.requested; + } + + public void setRequested(Date requested) { + this.requested = requested; + } + + public Date getExpiry() { + return this.expiry; + } + + public void setExpiry(Date expiry) { + this.expiry = expiry; + } + + public String getSiteName() { + return this.siteName; + } + + public void setSiteName(String siteName) { + this.siteName = siteName; + } + + public String getForWhat() { + return this.forWhat; + } + + public void setForWhat(String forWhat) { + this.forWhat = forWhat; + } +} diff --git a/src/main/java/com/midm/model/org/SiteInfo.java b/src/main/java/com/midm/model/org/SiteInfo.java new file mode 100644 index 0000000..65e56fb --- /dev/null +++ b/src/main/java/com/midm/model/org/SiteInfo.java @@ -0,0 +1,169 @@ +package com.midm.model.org; + +import com.google.common.base.Strings; +import com.mitac.cell.db.DbObject; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import org.springframework.data.mongodb.core.index.Indexed; + +public class SiteInfo { + @Indexed + private UUID siteUuid; + private Set roles; + private UUID groupUuid; + protected DbObject settings; + private Boolean apiOnly; + private Date created; + private Date updated; + private boolean enabled; + + public SiteInfo() { + this.setRoles(new HashSet()); + this.setCreated(new Date()); + this.setUpdated(new Date()); + this.setEnabled(false); + } + + public SiteInfo(UUID siteUuid) { + this(); + this.setSiteUuid(siteUuid); + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public Set getRoles() { + if (this.roles == null) { + this.roles = new HashSet(); + } + + return this.roles; + } + + public boolean hasRole(String role) { + return this.isEnabled() && !this.getRoles().isEmpty() && this.getRoles().contains(role); + } + + public boolean hasRole(Collection roles) { + if (this.isEnabled() && !this.getRoles().isEmpty()) { + for(String role : roles) { + if (this.getRoles().contains(role)) { + return true; + } + } + } + + return false; + } + + public void addRole(String role) { + role = UserRole.toRole(role); + if (!Strings.isNullOrEmpty(role)) { + this.getRoles().add(role); + } + + } + + public void setRoles(Set roles) { + if (roles != null && !roles.isEmpty()) { + for(String role : roles) { + role = UserRole.toRole(role); + if (!Strings.isNullOrEmpty(role) && !this.hasRole("SUPERVISOR")) { + if (role.equals("SUPERVISOR")) { + this.getRoles().clear(); + this.getRoles().add(role); + } else { + this.getRoles().add(role); + } + } + } + } else { + this.roles = null; + } + + } + + public void clearRoles() { + this.getRoles().clear(); + } + + public UUID getGroupUuid() { + return this.groupUuid; + } + + public void setGroupUuid(UUID groupUuid) { + this.groupUuid = groupUuid; + } + + public boolean isApiOnly() { + return this.apiOnly != null && this.apiOnly; + } + + public void setApiOnly(boolean apiOnly) { + this.apiOnly = apiOnly; + } + + public DbObject getSettings() { + if (this.settings == null) { + this.settings = new DbObject(); + } + + return this.settings; + } + + public void setSettings(DbObject settings) { + this.settings = settings; + } + + public void setSetting(String key, Object value) { + this.getSettings().put(key, value); + } + + public Object getSetting(String key) { + return this.getSettings().get(key); + } + + public String getSettingAsString(String key) { + return this.getSettings().getString(key, (String)null); + } + + public DbObject getPageSetting(String url) { + return this.getSettings().getDbObject(new String[]{"page", url}); + } + + public void setPageSetting(String url, String key, Object value) { + this.getPageSetting(url).put(key, value); + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getUpdated() { + return this.updated; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } + + public boolean isEnabled() { + return this.enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } +} diff --git a/src/main/java/com/midm/model/org/SiteLicense.java b/src/main/java/com/midm/model/org/SiteLicense.java new file mode 100644 index 0000000..69822f6 --- /dev/null +++ b/src/main/java/com/midm/model/org/SiteLicense.java @@ -0,0 +1,267 @@ +package com.midm.model.org; + +import com.google.common.base.Strings; +import com.midm.model.system.LicenseModel; +import com.mitac.cell.db.DbObject; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class SiteLicense { + @Id + private UUID uuid; + @DBRef + private Site site; + @DBRef + private Site childSite; + @Transient + private User writer; + @DBRef + private LicenseModel licenseModel; + private int amount; + private DbObject reference; + private String plan; + @Transient + private DbObject report; + private STATUS status; + private boolean enabled; + private Date updated; + private Date created; + + public SiteLicense() { + this.plan = "standard"; + this.status = SiteLicense.STATUS.UNKNOWN; + this.uuid = UUID.randomUUID(); + this.enabled = true; + this.setCreated(new Date()); + } + + public SiteLicense(Site site) { + this(); + this.setSite(site); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public Site getSite() { + return this.site; + } + + public void setSite(Site site) { + if (site.isChild()) { + this.site = site.getReseller(); + this.childSite = site; + } else { + this.site = site; + } + + } + + public Site getChildSite() { + return this.childSite; + } + + public boolean isForChildSite() { + return this.childSite != null; + } + + public void setChildSite(Site reseller) { + this.childSite = reseller; + } + + public User getWriter() { + return this.writer; + } + + public void setWriter(User user) { + this.writer = user; + } + + public String getPlan() { + return this.plan; + } + + public void setPlan(String plan) { + this.plan = plan; + } + + public boolean isLite() { + return "lite".equals(this.getPlan()); + } + + public LicenseModel getLicenseModel() { + return this.licenseModel; + } + + public void setLicenseModel(LicenseModel licenseModel) { + if (this.isUpdated() && !this.licenseModel.getUuid().equals(licenseModel.getUuid())) { + this.addNote("License model changed: " + licenseModel.getName()); + } + + this.licenseModel = licenseModel; + } + + public Character getType() { + return this.licenseModel.getType(); + } + + public Integer getPeriod() { + return this.licenseModel.getPeriod(); + } + + public int getAmount() { + return this.amount; + } + + public void setAmount(int amount) { + if (this.isUpdated() && this.amount != amount) { + this.addNote("Amount changed: " + amount); + } + + this.amount = amount; + } + + public DbObject getReference() { + if (this.reference == null) { + this.reference = new DbObject(); + } + + return this.reference; + } + + public void setReference(DbObject reference) { + this.reference = reference; + } + + public String getPo() { + return this.getReference().getString("po", ""); + } + + public void setPo(String po) { + if (this.isUpdated() && !this.getPo().equals(po)) { + this.addNote(Strings.isNullOrEmpty(po) ? "PO has unset" : "PO changed: " + po); + } + + this.getReference().put("po", po); + } + + public String getDesc() { + return this.getReference().getString("desc", ""); + } + + public void setDesc(String desc) { + this.getReference().put("desc", desc); + } + + public List getNotes() { + return this.getReference().getList("notes", DbObject.class); + } + + public void addNote(STATUS status) { + if (this.isUpdated()) { + this.addNote("Status changed: " + status); + } else { + this.addNote(String.format("%s: %s, %,d licenses", status, this.licenseModel.getName(), this.amount)); + } + + } + + public void addNote(String note) { + DbObject noteObj = new DbObject("name", this.writer.getName()); + noteObj.append("email", this.writer.getEmail()).append("note", note).append("updated", this.updated); + List notes = this.getNotes(); + if (notes == null) { + notes = new ArrayList(); + this.getReference().append("notes", notes); + } + + notes.add(noteObj); + } + + public boolean getEnabled() { + return this.enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public Date getUpdated() { + return this.updated; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } + + private boolean isUpdated() { + return !this.created.equals(this.updated); + } + + public void updated() { + this.updated = new Date(); + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + this.updated = created; + } + + public DbObject getReport() { + if (this.report == null) { + this.report = new DbObject(); + } + + return this.report; + } + + public void setReport(DbObject report) { + this.report = report; + } + + public void setReport(String key, Object value) { + this.getReport().put(key, value); + } + + public boolean isTrial() { + return this.getLicenseModel().isTrial(); + } + + public boolean isPerpetual() { + return this.getLicenseModel().isPerpetual(); + } + + public STATUS getStatus() { + return this.status; + } + + public void setStatus(STATUS status) { + this.addNote(status); + this.status = status; + } + + public static enum STATUS { + ORDERED, + PROCESSING, + CONFIRMED, + REJECTED, + CANCELED, + UNKNOWN; + } +} diff --git a/src/main/java/com/midm/model/org/SitePlan.java b/src/main/java/com/midm/model/org/SitePlan.java new file mode 100644 index 0000000..fc9e310 --- /dev/null +++ b/src/main/java/com/midm/model/org/SitePlan.java @@ -0,0 +1,47 @@ +package com.midm.model.org; + +import com.mitac.cell.db.DbObject; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class SitePlan { + @Id + private UUID uuid; + private String model = "midm"; + private DbObject plan; + private boolean isReseller = false; + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public String getModel() { + return this.model; + } + + public void setModel(String model) { + this.model = model; + } + + public DbObject getPlan() { + return this.plan; + } + + public void setPlan(DbObject plan) { + this.plan = plan; + } + + public boolean isReseller() { + return this.isReseller; + } + + public void setReseller(boolean isReseller) { + this.isReseller = isReseller; + } +} diff --git a/src/main/java/com/midm/model/org/SiteRequest.java b/src/main/java/com/midm/model/org/SiteRequest.java new file mode 100644 index 0000000..f9cd725 --- /dev/null +++ b/src/main/java/com/midm/model/org/SiteRequest.java @@ -0,0 +1,92 @@ +package com.midm.model.org; + +import java.util.Date; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class SiteRequest { + @Id + private UUID uuid; + private String name; + private String email; + private String company; + private String title; + private String phone; + private String country; + private String industry; + private Date requestedAt; + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return this.email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getCompany() { + return this.company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getPhone() { + return this.phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public String getCountry() { + return this.country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getIndustry() { + return this.industry; + } + + public void setIndustry(String industry) { + this.industry = industry; + } + + public Date getRequestedAt() { + return this.requestedAt; + } + + public void setRequestedAt(Date requestedAt) { + this.requestedAt = requestedAt; + } +} diff --git a/src/main/java/com/midm/model/org/USER_PROPERTY.java b/src/main/java/com/midm/model/org/USER_PROPERTY.java new file mode 100644 index 0000000..7a0a818 --- /dev/null +++ b/src/main/java/com/midm/model/org/USER_PROPERTY.java @@ -0,0 +1,31 @@ +package com.midm.model.org; + +public enum USER_PROPERTY { + email, + email_addr, + email_address, + role, + roles, + mail, + name, + password, + pwd, + group, + title, + position, + tel, + phone, + telephone, + mobile, + mobilephone, + mobile_phone, + unknown; + + public static USER_PROPERTY get(String key) { + try { + return valueOf(key.trim().toLowerCase()); + } catch (Exception var2) { + return unknown; + } + } +} diff --git a/src/main/java/com/midm/model/org/User.java b/src/main/java/com/midm/model/org/User.java new file mode 100644 index 0000000..de7467b --- /dev/null +++ b/src/main/java/com/midm/model/org/User.java @@ -0,0 +1,687 @@ +package com.midm.model.org; + +import com.google.api.client.util.Strings; +import com.google.gson.annotations.Expose; +import com.midm.constant.LocaleConst; +import com.midm.model.GeneralProfile; +import com.midm.model.system.PolicyAgreement; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McEmailUtils; +import com.mitac.cell.utils.McStringUtils; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Document +public class User extends GeneralProfile { + public static final int MAX_LOGIN_ATTEMPT = 5; + public static final int LOGIN_AFTER_MINUTES = 10; + @Indexed + private UUID siteUuid; + @Indexed + private String email; + @Expose( + serialize = false + ) + private String password; + private List sites; + @Transient + private boolean isMultiSiteUser; + @Transient + private boolean isApiUser; + @Transient + private SiteInfo siteInfo; + private Set systemRoles; + @Transient + private UUID groupUuid; + protected Date activated; + @Transient + private Site site; + @Transient + private UserGroup userGroup; + + public User() { + } + + public User(UUID userUuid) { + this.setUuid(userUuid); + } + + public User(String email) { + this(); + this.setEmail(email); + } + + public User(String email, String password) { + this(email); + this.setPassword(password); + } + + public void init() { + super.init(); + if (this.hasRole("SUPERVISOR") || this.hasSystemRole("SYSTEM_ADMIN")) { + this.setEnabled(true); + } + + this.setActivated(); + if (Strings.isNullOrEmpty(super.getName())) { + this.setName(this.getName()); + } + + } + + public UUID getSiteUuid() { + if (this.siteUuid == null && !this.hasSystemRole()) { + List sites = this.getSites(); + if (!sites.isEmpty()) { + this.setSiteUuid(((SiteInfo)sites.get(0)).getSiteUuid()); + } + } + + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + SiteInfo siteInfo = this.getSiteInfo(siteUuid); + if (siteInfo != null) { + this.setRoles(siteInfo.getRoles()); + } + + } + + public Site getSite() { + return this.site; + } + + public void setSite(Site site) { + this.site = site; + } + + public boolean isReseller() { + return this.site != null && this.site.isReseller(); + } + + public boolean isLite() { + return this.site != null && this.site.isLite(); + } + + public boolean isStandard() { + return this.site != null && this.site.isStandard(); + } + + public boolean isStandardWithBatteryPro() { + return this.site != null && this.site.isStandardWithBatteryPro(); + } + + public boolean isFeatureAllowed(String subCategory, String item) { + return this.isLite() ? this.site != null && this.site.isFeatureAllowed(subCategory, item) : true; + } + + public boolean isFilesFeatureAllowed(String category, String key) { + return this.isFeatureAllowed(category, key) && (this.hasRole("SUPERVISOR") || this.hasRole("PROFILE_MANAGER")); + } + + public String getEmail() { + return this.email; + } + + public void setEmail(String email) { + if (!Strings.isNullOrEmpty(email)) { + if (McEmailUtils.isValid(email)) { + this.email = email.toLowerCase(); + } + + if (Strings.isNullOrEmpty(super.getName())) { + this.setName(this.getName()); + } + + } + } + + public String getPassword() { + return this.password; + } + + public boolean setPassword(String password) { + this.password = password; + return !Strings.isNullOrEmpty(password) && password.length() >= 8 ? McStringUtils.hasUpperLowerDigit(password) : false; + } + + public String getName() { + String name = super.getName(); + if (Strings.isNullOrEmpty(name)) { + name = this.getEmail().substring(0, this.getEmail().indexOf("@")); + } + + return name; + } + + public void setSiteInfo(SiteInfo siteInfo) { + this.siteInfo = siteInfo; + } + + public List getSites() { + if (this.sites == null) { + this.sites = new ArrayList(); + } + + return this.sites; + } + + public List getSiteUuids() { + return this.sites != null && !this.sites.isEmpty() ? (List)this.sites.stream().map((item) -> item.getSiteUuid()).collect(Collectors.toList()) : null; + } + + public boolean clearUndefinedSites() { + boolean hasChanges = false; + if (this.sites != null) { + Iterator it = this.sites.iterator(); + + while(it.hasNext()) { + SiteInfo site = (SiteInfo)it.next(); + if (site.getSiteUuid() == null) { + it.remove(); + hasChanges = true; + } + } + } + + return hasChanges; + } + + public void setSites(List sites) { + this.sites = sites; + } + + public boolean isMultiSiteUser() { + return this.isMultiSiteUser; + } + + public void setMultiSiteUser() { + this.isMultiSiteUser = this.getSites().size() > 1; + if (!this.isMultiSiteUser) { + this.isApiUser = this.isApiUser(); + } + + } + + public SiteInfo getSiteInfo() { + return this.getSiteInfo(this.getSiteUuid()); + } + + public SiteInfo getSiteInfo(Site site) { + return this.getSiteInfo(site.getUuid()); + } + + public SiteInfo getSiteInfo(UUID siteUuid) { + if (siteUuid == null) { + return null; + } else { + for(SiteInfo siteInfo : this.getSites()) { + if (siteInfo.getSiteUuid() != null && siteInfo.getSiteUuid().equals(siteUuid)) { + return siteInfo; + } + } + + return null; + } + } + + public boolean isBelongedToSite(Site site) { + return this.isBelongedToSite(site.getUuid()); + } + + public boolean isBelongedToSite(UUID siteUuid) { + for(SiteInfo siteInfo : this.getSites()) { + if (siteInfo.getSiteUuid() != null && siteInfo.getSiteUuid().equals(siteUuid)) { + return true; + } + } + + return false; + } + + public boolean canHandle(UUID siteUuid, String... roles) { + SiteInfo info = this.getSiteInfo(siteUuid); + if (info != null) { + if (info.hasRole("SUPERVISOR")) { + return true; + } + + for(String role : roles) { + if (info.hasRole(role)) { + return true; + } + } + } + + return false; + } + + public SiteInfo addSite(UUID siteUuid) { + if (siteUuid == null) { + return null; + } else { + if (!this.isBelongedToSite(siteUuid)) { + this.getSites().add(new SiteInfo(siteUuid)); + } + + if (this.getSiteUuid() == null) { + this.setSiteUuid(siteUuid); + } + + SiteInfo siteInfo = this.getSiteInfo(siteUuid); + siteInfo.setEnabled(true); + return siteInfo; + } + } + + public void removeSite(UUID siteUuid) { + if (siteUuid != null) { + SiteInfo existSite = null; + + for(SiteInfo siteInfo : this.getSites()) { + if (siteInfo.getSiteUuid().equals(siteUuid)) { + existSite = siteInfo; + break; + } + } + + if (existSite != null) { + this.getSites().remove(existSite); + } + + if (this.getSites().isEmpty()) { + this.setSiteUuid((UUID)null); + this.setGroupUuid((UUID)null); + this.setLastSite((UUID)null); + } else { + if (siteUuid.equals(this.getSiteUuid())) { + this.setSiteUuid((UUID)null); + this.setGroupUuid((UUID)null); + } + + if (siteUuid.equals(this.getLastSite())) { + this.setLastSite((UUID)null); + } + } + + } + } + + public Set getRoles() { + return this.getRolesBySite(this.getSiteUuid()); + } + + public Set getRoles(UUID siteUuid) { + return this.getRolesBySite(siteUuid); + } + + public Set getRolesBySite(UUID siteUuid) { + SiteInfo info = this.getSiteInfo(siteUuid); + return (Set)(info != null ? this.getSiteInfo(siteUuid).getRoles() : new HashSet()); + } + + public void setRoles(Set roles) { + SiteInfo info = this.getSiteInfo(this.getSiteUuid()); + if (info != null) { + this.getSiteInfo(this.getSiteUuid()).setRoles(roles); + } + + } + + public void addRoleToSite(String role, UUID siteUuid) { + role = UserRole.toRole(role); + if (role != null) { + if (role.equals("SUPERVISOR")) { + this.getRoles(siteUuid).clear(); + } + + this.getRolesBySite(siteUuid).add(role); + } + + } + + public void removeRole(String role) { + this.getRoles().remove(role); + } + + public void removeRole(UUID siteUuid, String role) { + SiteInfo siteInfo = this.getSiteInfo(siteUuid); + if (siteInfo != null) { + siteInfo.getRoles().remove(role); + } + + } + + public Set getSystemRoles() { + if (this.systemRoles == null) { + this.systemRoles = new HashSet(); + } + + return this.systemRoles; + } + + public void setSystemRoles(Set systemRoles) { + this.systemRoles = systemRoles; + } + + public void addSystemRole(String role) { + this.getSystemRoles().add(role); + } + + public void removeSystemRole(String role) { + this.getSystemRoles().remove(role); + } + + public boolean hasSystemRole() { + return !this.getSystemRoles().isEmpty(); + } + + public boolean hasSystemRole(String role) { + return this.getSystemRoles().contains(role); + } + + public boolean hasRole(String role) { + return this.hasRole(this.getSiteUuid(), role); + } + + public boolean hasRole(UUID siteUuid, String role) { + SiteInfo site = this.getSiteInfo(siteUuid); + return site != null ? site.hasRole(role) : false; + } + + public boolean isSupervisor() { + return this.hasRole("SUPERVISOR"); + } + + public boolean isSystemUser() { + return !this.getSystemRoles().isEmpty(); + } + + public boolean isSystemAdmin() { + return this.getSystemRoles().contains("SYSTEM_ADMIN"); + } + + public UUID getGroupUuid() { + return this.groupUuid; + } + + public void setGroupUuid(UUID groupUuid) { + this.groupUuid = groupUuid; + } + + public Date getActivated() { + return this.activated; + } + + public void setActivated(Date activated) { + this.activated = activated; + } + + public void setActivated() { + this.activated = new Date(); + this.enabled = true; + } + + public boolean isActivated() { + return true; + } + + public boolean isAvailable() { + return this.getEnabled() && this.isActivated(); + } + + public String getEmailAddress() { + String EMAIL_FORMAT = "%s<%s>"; + String name = this.getName(); + if (McStringUtils.isNullOrEmpty(this.email)) { + return null; + } else { + return McStringUtils.isNullOrEmpty(name) ? this.email : String.format("%s<%s>", name, this.email); + } + } + + public UserGroup getUserGroup() { + return this.userGroup; + } + + public void setUserGroup(UserGroup userGroup) { + this.userGroup = userGroup; + if (userGroup != null) { + SiteInfo siteInfo = this.getSiteInfo(userGroup.getSiteUuid()); + if (siteInfo != null) { + siteInfo.setGroupUuid(userGroup.getUuid()); + } else { + this.userGroup = null; + } + } + + } + + public void encodePassword(PasswordEncoder encoder, String password) { + this.password = encoder.encode(password); + } + + public void encodePassword(PasswordEncoder encoder) { + this.password = encoder.encode(this.password); + } + + public boolean canRegister() { + return !McStringUtils.isNullOrEmpty(this.getEmail()) && !McStringUtils.isNullOrEmpty(this.getPassword()); + } + + public List getAuthorities() { + return UserRole.getAuthorities(this.getRoles()); + } + + public String getTheme() { + String theme = "default"; + if (this.site != null) { + String model = this.site.getModel(); + if (!Strings.isNullOrEmpty(model) && !model.equals("midm")) { + theme = model; + } + } + + return theme; + } + + public String getLocale() { + String locale = this.getSettingAsString("language"); + return McStringUtils.isNullOrEmpty(locale) ? LocaleConst.DEFAULT_LOCALE.toLanguageTag() : locale; + } + + public void setLocale(Locale locale) { + this.setLocale(locale.toLanguageTag()); + } + + public void setLocale(String locale) { + this.setSetting("language", locale); + } + + public boolean isSameLocale(Locale locale) { + return this.isSameLocale(locale.toLanguageTag()); + } + + public boolean isSameLocale(String localeTag) { + return this.getLocale().equals(localeTag); + } + + public boolean keepSignIn() { + return this.getSettingAsBoolean("keepSignIn"); + } + + public UUID getLastSite() { + UUID uuid = this.getSettingAsUuid("lastSite"); + if (uuid == null && this.sites != null && !this.sites.isEmpty() && !this.hasSystemRole()) { + uuid = ((SiteInfo)this.sites.get(0)).getSiteUuid(); + this.setLastSite(uuid); + } + + return uuid; + } + + public void setLastSite(UUID uuid) { + this.setSetting("lastSite", uuid); + } + + public String getLastPage() { + SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); + return siteInfo == null ? this.getSettingAsString("lastPage") : siteInfo.getSettingAsString("lastPage"); + } + + public List getDashboardSettings() { + SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); + if (siteInfo != null) { + Object settings = siteInfo.getSetting("dashboard"); + if (settings != null && settings instanceof List) { + return (List)settings; + } + } + + return new ArrayList(); + } + + public DbObject getReportSettings() { + SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); + return siteInfo != null ? siteInfo.getSettings().getDbObject(new String[]{"report"}) : new DbObject(); + } + + public void setDashboardSettings(List dashboard) { + SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); + if (siteInfo != null) { + siteInfo.setSetting("dashboard", dashboard); + } + + } + + public void setLastPage(String url) { + SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); + if (siteInfo != null) { + siteInfo.setSetting("lastPage", url); + } + + } + + public DbObject getPageSettings(String pageUrl) { + Object settings = this.getSetting("page", pageUrl); + DbObject var3; + if (settings == null) { + var3 = new DbObject(); + } else { + if (settings instanceof DbObject) { + return (DbObject)settings; + } + + if (settings instanceof Map) { + var3 = new DbObject((Map)settings); + } else { + var3 = new DbObject(); + } + } + + this.setSetting("page", pageUrl, var3); + return var3; + } + + public Object getPageSetting(String pageUrl, String key) { + return this.getPageSettings(pageUrl).get(key); + } + + public void setPageSetting(String pageUrl, String key, Object value) { + if (value == null) { + this.getPageSettings(pageUrl).remove(key); + } else { + this.getPageSettings(pageUrl).put(key, value); + } + + } + + public void updateProfile(DbObject newProfile) { + DbObject profile = this.getProfile(); + newProfile.forEach((key, value) -> { + if (!key.equals("eula") && !key.equals("ip")) { + profile.put(key, value); + } + + }); + } + + public void setEula(PolicyAgreement agreement) { + this.setProfile("eula", (new DbObject("uuid", agreement.getUuid().toString())).append("version", agreement.getVersion()).append("acceptDate", new Date())); + } + + public void setEula(String value) { + Object object = McStringUtils.isNullOrEmpty(value) ? new DbObject() : DbObject.parse(value); + this.setProfile("eula", object); + } + + public String getMfaMethod() { + return this.getSettingAsString("mfa"); + } + + public boolean isEulaAgreed() { + return this.isApiUser() || this.getCategoryProfile("eula", "acceptDate") != null; + } + + public boolean isApiUser() { + SiteInfo siteInfo = this.getSiteInfo(); + return siteInfo != null && siteInfo.isApiOnly(); + } + + public boolean equals(Object user) { + if (user == null) { + return false; + } else if (user instanceof User) { + return this.getEmail().equalsIgnoreCase(((User)user).getEmail()); + } else if (user instanceof String) { + return this.getEmail().equals((String)user); + } else { + return user instanceof UUID ? user.equals(this.getUuid()) : super.equals(user); + } + } + + public void setProfileOnly() { + this.siteUuid = null; + this.sites = null; + this.systemRoles = null; + this.activated = null; + this.settings = null; + this.created = null; + this.updated = null; + this.getProfile().remove("eula"); + } + + public DbObject getLoginAttempt() { + return this.getSettings().getDbObject(new String[]{"loginAttempt"}); + } + + public void loginFailed() { + DbObject loginAttempt = this.getLoginAttempt(); + loginAttempt.put("attemptAt", new Date()); + int count = loginAttempt.getInteger("count", 0) + 1; + loginAttempt.put("count", count % 6); + this.setSetting("loginAttempt", loginAttempt); + } + + public void resetLoginAttempt() { + this.getSettings().remove("loginAttempt"); + } + + public String toString() { + return this.getEmail(); + } +} diff --git a/src/main/java/com/midm/model/org/UserAccess.java b/src/main/java/com/midm/model/org/UserAccess.java new file mode 100644 index 0000000..cab8e0a --- /dev/null +++ b/src/main/java/com/midm/model/org/UserAccess.java @@ -0,0 +1,13 @@ +package com.midm.model.org; + +import java.util.Date; +import java.util.UUID; + +public class UserAccess { + private String sessionId; + private UUID userUuid; + private String browser; + private String os; + private String device; + private Date lastAccess; +} diff --git a/src/main/java/com/midm/model/org/UserGroup.java b/src/main/java/com/midm/model/org/UserGroup.java new file mode 100644 index 0000000..d56ab13 --- /dev/null +++ b/src/main/java/com/midm/model/org/UserGroup.java @@ -0,0 +1,57 @@ +package com.midm.model.org; + +import com.midm.model.GeneralProfile; +import java.util.UUID; +import org.springframework.data.annotation.Transient; + +public class UserGroup extends GeneralProfile { + private UUID siteUuid; + private UUID parentUuid; + private Integer order; + @Transient + private Long userNumbers; + + public UserGroup() { + } + + public UserGroup(UUID siteUuid, UserGroup parentGroup, String name) { + this.setSiteUuid(siteUuid); + if (parentGroup != null) { + this.setParentUuid(parentGroup.getUuid()); + } + + this.setName(name); + } + + public UUID getSiteUuid() { + return this.siteUuid; + } + + public void setSiteUuid(UUID siteUuid) { + this.siteUuid = siteUuid; + } + + public UUID getParentUuid() { + return this.parentUuid; + } + + public void setParentUuid(UUID parentUuid) { + this.parentUuid = parentUuid; + } + + public Integer getOrder() { + return this.order; + } + + public void setOrder(Integer order) { + this.order = order; + } + + public Long getUserNumbers() { + return this.userNumbers; + } + + public void setUserNumbers(Long numbers) { + this.userNumbers = numbers; + } +} diff --git a/src/main/java/com/midm/model/org/UserRole.java b/src/main/java/com/midm/model/org/UserRole.java new file mode 100644 index 0000000..4c2bb1c --- /dev/null +++ b/src/main/java/com/midm/model/org/UserRole.java @@ -0,0 +1,73 @@ +package com.midm.model.org; + +import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +public class UserRole { + public static final String ROLES = "roles"; + public static final String SYSTEM_ROLES = "systemRoles"; + public static final String ROLE_SUPER_USER = "SUPER_USER"; + public static final String ROLE_SUPERVISOR = "SUPERVISOR"; + public static final String ROLE_SYSTEM_ADMIN = "SYSTEM_ADMIN"; + public static final String ROLE_SITE_MANAGER = "SITE_MANAGER"; + public static final String ROLE_SALES = "SALES"; + public static final String ROLE_RESELLER = "RESELLER"; + public static final String ROLE_FINANCE = "FINANCE"; + public static final String ROLE_USER = "USER"; + public static final String ROLE_USER_MANAGER = "USER_MANAGER"; + public static final String ROLE_DEVICE_MANAGER = "DEVICE_MANAGER"; + public static final String ROLE_PROFILE_MANAGER = "PROFILE_MANAGER"; + public static final String ROLE_DEVIE_OWNER = "DEVICE_OWNER"; + public static final String ROLE_GUEST = "ROLE_GUEST"; + public static final String[] USER_MANAGE_ROLES = new String[]{"SUPERVISOR", "USER_MANAGER"}; + public static final String[] DEVICE_MANAGE_ROLES = new String[]{"SUPERVISOR", "DEVICE_MANAGER"}; + public static final String[] PROFILE_MANAGE_ROLES = new String[]{"SUPERVISOR", "PROFILE_MANAGER"}; + + public static List getAuthorities(final String role) { + return new ArrayList() { + { + this.add(new SimpleGrantedAuthority(role)); + } + }; + } + + public static List getAuthorities(final Set roles) { + return new ArrayList() { + { + if (roles != null && !roles.isEmpty()) { + for(String role : roles) { + this.add(new SimpleGrantedAuthority(role)); + } + } else { + this.add(new SimpleGrantedAuthority("ROLE_GUEST")); + } + + } + }; + } + + public static String toRole(String role) { + if (Strings.isNullOrEmpty(role)) { + return null; + } else { + switch (role.toLowerCase()) { + case "supervisor": + return "SUPERVISOR"; + case "user_manager": + case "usermanager": + return "USER_MANAGER"; + case "device_manager": + case "devicemanager": + return "DEVICE_MANAGER"; + case "profile_manager": + case "profilemanager": + return "PROFILE_MANAGER"; + default: + return null; + } + } + } +} diff --git a/src/main/java/com/midm/model/org/UserToken.java b/src/main/java/com/midm/model/org/UserToken.java new file mode 100644 index 0000000..922d1c4 --- /dev/null +++ b/src/main/java/com/midm/model/org/UserToken.java @@ -0,0 +1,173 @@ +package com.midm.model.org; + +import com.google.common.base.Strings; +import com.google.gson.annotations.Expose; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McUrlUtils; +import com.mitac.cell.utils.McUuidUtils; +import java.io.Serializable; +import java.util.Date; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.joda.time.DateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class UserToken implements Serializable { + public static final char TOKEN_CONFIRMATION = 'C'; + public static final char TOKEN_ACTIVATION = 'A'; + public static final char TOKEN_LOGIN = 'L'; + public static final char TOKEN_REMEMBER_LOGIN = 'R'; + public static final char TOKEN_RESET_PASSWORD = 'P'; + public static final char TOKEN_MFA_AUTH = 'M'; + public static final char TOKEN_DEVICE_ACCESS = 'D'; + @Id + @Expose( + serialize = false + ) + private UUID tokenUuid; + @Transient + private String accessToken; + @Expose( + serialize = false + ) + private UUID userUuid; + @Expose( + serialize = false + ) + private char tokenType; + @Expose( + serialize = false + ) + private Date created; + @Expose( + serialize = false + ) + private Date expired; + private DbObject reference; + + public UserToken() { + } + + public UserToken(User user, char tokenType, long validPeriod) { + this.tokenUuid = UUID.randomUUID(); + this.userUuid = user.getUuid(); + this.tokenType = tokenType; + this.created = new Date(); + DateTime date = new DateTime(this.created); + this.expired = date.plus(validPeriod).toDate(); + } + + public void renew() { + this.tokenUuid = UUID.randomUUID(); + this.encryptToken(); + this.created = new Date(); + long validPeriod = this.expired.getTime() - this.created.getTime(); + DateTime date = new DateTime(this.created); + this.expired = date.plus(validPeriod).toDate(); + } + + public void encryptToken() { + this.accessToken = McUuidUtils.toBase64String(this.tokenUuid); + } + + public String getAccessToken() { + if (Strings.isNullOrEmpty(this.accessToken)) { + this.encryptToken(); + } + + return this.accessToken; + } + + public UUID getTokenUuid() { + return this.tokenUuid; + } + + public void setTokenUuid(UUID uid) { + this.tokenUuid = uid; + } + + public UUID getUserUuid() { + return this.userUuid; + } + + public void setUserUuid(UUID userUuid) { + this.userUuid = userUuid; + } + + public char getTokenType() { + return this.tokenType; + } + + public void setTokenType(char tokenType) { + this.tokenType = tokenType; + } + + public String getMfaToken(int length) { + return this.getMfaToken().substring(0, length); + } + + public String getMfaToken() { + return String.valueOf(this.tokenUuid.getMostSignificantBits() * this.tokenUuid.getLeastSignificantBits()); + } + + public DbObject getReference() { + if (this.reference == null) { + this.reference = new DbObject(); + } + + return this.reference; + } + + public void setReference(DbObject reference) { + this.reference = reference; + } + + public void setReference(String key, Object value) { + if (value == null) { + this.getReference().remove(key); + } else { + this.getReference().put(key, value); + } + + } + + public UUID getDeviceUuid() { + return this.getReference().getUuid("deviceUuid"); + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date registered) { + this.created = registered; + } + + public Date getExpired() { + return this.expired; + } + + public void setExpired(Date expired) { + this.expired = expired; + } + + public void plusExpired(long time) { + DateTime expiredDate = new DateTime(this.getExpired()); + expiredDate.plus(time); + } + + public boolean isExpired() { + return this.getExpired().getTime() < (new Date()).getTime(); + } + + public DbObject toDeviceAccess(HttpServletRequest request) { + String var10000 = McUrlUtils.getHostUrl(request); + String accessUrl = var10000 + "/device/" + McUuidUtils.toBase64String(this.tokenUuid, true); + DbObject deviceAccess = new DbObject("accessUrl", accessUrl); + deviceAccess.append("expiry", this.getExpired()); + return deviceAccess; + } +} diff --git a/src/main/java/com/midm/model/store/AppReleaseNote.java b/src/main/java/com/midm/model/store/AppReleaseNote.java new file mode 100644 index 0000000..20efa49 --- /dev/null +++ b/src/main/java/com/midm/model/store/AppReleaseNote.java @@ -0,0 +1,85 @@ +package com.midm.model.store; + +import java.io.Serializable; +import java.util.List; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class AppReleaseNote extends ReleaseNote { + @Id + private NoteId noteId; + private String versionName; + private int minSdkVersion; + private List files; + + public AppReleaseNote() { + } + + public AppReleaseNote(String packageName, int versionCode, String versionName, int minSdkVersion) { + this.noteId = new NoteId(packageName, versionCode); + this.versionName = versionName; + this.setMinSdkVersion(minSdkVersion); + } + + public AppReleaseNote(StoreAppFile appFile) { + this(appFile.getPackageName(), (int)appFile.getVersionCode(), appFile.getVersionName(), appFile.getMinSdkVersion()); + } + + public int getVersionCode() { + return this.noteId.getVersionCode(); + } + + public String getVersionName() { + return this.versionName; + } + + public void setVersionName(String versionName) { + this.versionName = versionName; + } + + public List getFiles() { + return this.files; + } + + public void setFiles(List files) { + this.files = files; + } + + public int getMinSdkVersion() { + return this.minSdkVersion; + } + + public void setMinSdkVersion(int minSdkVersion) { + this.minSdkVersion = minSdkVersion; + } + + public static class NoteId implements Serializable { + private String packageName; + private int versionCode; + + public NoteId() { + } + + public NoteId(String packageName, int versionCode) { + this.packageName = packageName; + this.versionCode = versionCode; + } + + public String getAppUuid() { + return this.packageName; + } + + public void setAppUuid(String packageName) { + this.packageName = packageName; + } + + public int getVersionCode() { + return this.versionCode; + } + + public void setVersionCode(int versionCode) { + this.versionCode = versionCode; + } + } +} diff --git a/src/main/java/com/midm/model/store/KeyStore.java b/src/main/java/com/midm/model/store/KeyStore.java new file mode 100644 index 0000000..d324b6b --- /dev/null +++ b/src/main/java/com/midm/model/store/KeyStore.java @@ -0,0 +1,85 @@ +package com.midm.model.store; + +import com.mitac.cell.io.McFile; +import java.io.InputStream; +import java.security.Key; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class KeyStore { + @Id + private String id; + private String description; + private String alias; + private String keyPassword; + private String storePassword; + private String certMd5; + + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getAlias() { + return this.alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public String getKeyPassword() { + return this.keyPassword; + } + + public void setKeyPassword(String keyPassword) { + this.keyPassword = keyPassword; + } + + public String getStorePassword() { + return this.storePassword; + } + + public void setStorePassword(String storePassword) { + this.storePassword = storePassword; + } + + public String getCertMd5() { + return this.certMd5; + } + + public void setCertMd5(String certMd5) { + this.certMd5 = certMd5; + } + + public void setCertMd5(McFile storeFile) { + try { + InputStream input = storeFile.getInputStream(); + java.security.KeyStore keystore = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType()); + keystore.load(input, this.storePassword.toCharArray()); + Key key = keystore.getKey(this.alias, this.keyPassword.toCharArray()); + if (key instanceof PrivateKey) { + Certificate cert = keystore.getCertificate(this.alias); + this.certMd5 = DigestUtils.md5Hex(cert.getEncoded()); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + } +} diff --git a/src/main/java/com/midm/model/store/OtaReleaseNote.java b/src/main/java/com/midm/model/store/OtaReleaseNote.java new file mode 100644 index 0000000..b804929 --- /dev/null +++ b/src/main/java/com/midm/model/store/OtaReleaseNote.java @@ -0,0 +1,60 @@ +package com.midm.model.store; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class OtaReleaseNote extends ReleaseNote { + @Id + private NoteId noteId; + private String displayId; + + public OtaReleaseNote() { + } + + public OtaReleaseNote(String productId, long buildDate) { + this.noteId = new NoteId(productId, buildDate); + } + + public OtaReleaseNote(StoreOtaFile otaFile) { + this(otaFile.getProductId(), otaFile.getBuildDate()); + this.setDisplayId(otaFile.getDisplayId()); + } + + public String getDisplayId() { + return this.displayId; + } + + public void setDisplayId(String versionName) { + this.displayId = versionName; + } + + public class NoteId { + private String productId; + private long buildDate; + + public NoteId() { + } + + public NoteId(String productId, long buildDate) { + this.productId = productId; + this.buildDate = buildDate; + } + + public String getProductId() { + return this.productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public long getBuildDate() { + return this.buildDate; + } + + public void setBuildDate(long buildDate) { + this.buildDate = buildDate; + } + } +} diff --git a/src/main/java/com/midm/model/store/ReleaseNote.java b/src/main/java/com/midm/model/store/ReleaseNote.java new file mode 100644 index 0000000..6a84a28 --- /dev/null +++ b/src/main/java/com/midm/model/store/ReleaseNote.java @@ -0,0 +1,50 @@ +package com.midm.model.store; + +import java.util.Date; + +public class ReleaseNote { + private String[] note; + private String[] noteNewFunction; + private Boolean isFormal; + private Date releasedAt = new Date(); + + public Date getReleasedAt() { + return this.releasedAt; + } + + public void setReleasedAt(Date releasedAt) { + this.releasedAt = releasedAt; + } + + public boolean hasNote() { + return this.note != null && this.note.length > 0; + } + + public boolean hasNoteNewFunction() { + return this.noteNewFunction != null && this.noteNewFunction.length > 0; + } + + public String[] getNote() { + return this.note; + } + + public void setNotes(String[] note) { + this.note = note; + } + + public String[] getNoteNewFunction() { + return this.noteNewFunction; + } + + public void setNoteNewFunctions(String[] noteNewFunction) { + this.noteNewFunction = noteNewFunction; + } + + public Boolean isFormal() { + return this.isFormal; + } + + public void setIsFormal(Boolean isFormal) { + this.isFormal = isFormal; + } +} diff --git a/src/main/java/com/midm/model/store/StoreApp.java b/src/main/java/com/midm/model/store/StoreApp.java new file mode 100644 index 0000000..8eda891 --- /dev/null +++ b/src/main/java/com/midm/model/store/StoreApp.java @@ -0,0 +1,73 @@ +package com.midm.model.store; + +import com.mitac.cell.db.DbObject; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class StoreApp extends StoreBase { + @Id + private String packageName; + private Boolean isFormal; + private DbObject appInfo; + @Transient + private Set sdkVersions; + + public StoreApp(String packageName) { + this.packageName = packageName; + } + + public Boolean isFormal() { + return this.isFormal; + } + + public void setIsFormal(Boolean isFormal) { + this.isFormal = isFormal; + } + + public String getPackageName() { + return this.packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public DbObject getAppInfo() { + if (this.appInfo == null) { + this.appInfo = new DbObject(); + } + + return this.appInfo; + } + + public void setAppInfo(DbObject appInfo) { + this.appInfo = appInfo; + } + + public void setAppInfo(String key, Object value) { + this.getAppInfo().append(key, value); + } + + public Set getSdkVersions() { + return this.sdkVersions; + } + + public void setSdkVersions(Set sdkVersions) { + this.sdkVersions = sdkVersions; + } + + public void setSdkVersions(List sdkVersions) { + if (sdkVersions != null) { + this.sdkVersions = new HashSet(); + this.sdkVersions.addAll(sdkVersions); + } else { + this.sdkVersions = null; + } + + } +} diff --git a/src/main/java/com/midm/model/store/StoreAppFile.java b/src/main/java/com/midm/model/store/StoreAppFile.java new file mode 100644 index 0000000..84654bd --- /dev/null +++ b/src/main/java/com/midm/model/store/StoreAppFile.java @@ -0,0 +1,17 @@ +package com.midm.model.store; + +import com.midm.model.file.AppFile; +import com.midm.model.org.User; +import com.mitac.cell.io.McFile; +import java.util.UUID; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class StoreAppFile extends AppFile { + public StoreAppFile() { + } + + public StoreAppFile(User user, UUID fileUuid, McFile file, boolean generateIcon) { + super(user, fileUuid, file, generateIcon); + } +} diff --git a/src/main/java/com/midm/model/store/StoreBase.java b/src/main/java/com/midm/model/store/StoreBase.java new file mode 100644 index 0000000..e2eaf6b --- /dev/null +++ b/src/main/java/com/midm/model/store/StoreBase.java @@ -0,0 +1,86 @@ +package com.midm.model.store; + +import com.midm.constant.LocaleConst; +import com.mitac.cell.db.DbObject; +import java.util.Date; + +public class StoreBase { + private DbObject title; + private DbObject summary; + private DbObject desc; + private Date createdAt = new Date(); + private Date lastUpdated = new Date(); + + public void init() { + this.createdAt = new Date(); + this.lastUpdated = new Date(); + } + + public DbObject getTitle() { + if (this.title == null) { + this.title = new DbObject(); + } + + return this.title; + } + + public void setTitle(DbObject title) { + this.title = title; + } + + public void setTitle(String key, Object value) { + this.getTitle().append(key, value); + } + + public void setTitle(String title) { + this.setTitle(LocaleConst.DEFAULT_LOCALE.toLanguageTag(), title); + } + + public DbObject getSummary() { + if (this.summary == null) { + this.summary = new DbObject(); + } + + return this.summary; + } + + public void setSummary(DbObject summary) { + this.summary = summary; + } + + public void setSummary(String key, Object value) { + this.getSummary().append(key, value); + } + + public DbObject getDesc() { + if (this.desc == null) { + this.desc = new DbObject(); + } + + return this.desc; + } + + public void setDescription(DbObject desc) { + this.desc = desc; + } + + public void setDescription(String key, Object value) { + this.getDesc().append(key, value); + } + + public Date getCreatedAt() { + return this.createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Date getLastUpdated() { + return this.lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } +} diff --git a/src/main/java/com/midm/model/store/StoreOta.java b/src/main/java/com/midm/model/store/StoreOta.java new file mode 100644 index 0000000..7ad00c0 --- /dev/null +++ b/src/main/java/com/midm/model/store/StoreOta.java @@ -0,0 +1,71 @@ +package com.midm.model.store; + +import com.mitac.cell.db.DbObject; +import java.util.Date; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class StoreOta { + @Id + private String productId; + private String deviceId; + private DbObject otaInfo; + private Boolean isFormal; + private Date createdAt; + private Date lastUpdated; + + public StoreOta(String productId) { + this.productId = productId; + this.createdAt = new Date(); + this.lastUpdated = new Date(); + } + + Boolean isFormal() { + return this.isFormal; + } + + public void setIsFormal(Boolean isFormal) { + this.isFormal = isFormal; + } + + public String getProductId() { + return this.productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getDeviceId() { + return this.deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public Date getCreatedAt() { + return this.createdAt; + } + + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Date getLastUpdated() { + return this.lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public DbObject getOtaInfo() { + return this.otaInfo; + } + + public void setOtaInfo(DbObject otaInfo) { + this.otaInfo = otaInfo; + } +} diff --git a/src/main/java/com/midm/model/store/StoreOtaFile.java b/src/main/java/com/midm/model/store/StoreOtaFile.java new file mode 100644 index 0000000..095d6c8 --- /dev/null +++ b/src/main/java/com/midm/model/store/StoreOtaFile.java @@ -0,0 +1,27 @@ +package com.midm.model.store; + +import com.midm.model.file.OtaFile; +import com.midm.model.org.User; +import com.mitac.cell.io.McFile; +import java.util.UUID; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class StoreOtaFile extends OtaFile { + private String[] note; + + public StoreOtaFile() { + } + + public StoreOtaFile(User user, UUID fileUuid, McFile file) { + super(user, fileUuid, file); + } + + public String[] getNote() { + return this.note; + } + + public void setNotes(String[] note) { + this.note = note; + } +} diff --git a/src/main/java/com/midm/model/store/StoreOtherFile.java b/src/main/java/com/midm/model/store/StoreOtherFile.java new file mode 100644 index 0000000..ac4cb31 --- /dev/null +++ b/src/main/java/com/midm/model/store/StoreOtherFile.java @@ -0,0 +1,27 @@ +package com.midm.model.store; + +import com.midm.model.file.BaseFile; +import com.midm.model.org.User; +import com.mitac.cell.io.McFile; +import java.util.UUID; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class StoreOtherFile extends BaseFile { + private String alias; + + public StoreOtherFile() { + } + + public StoreOtherFile(User user, UUID fileUuid, McFile file) { + super(user, fileUuid, file); + } + + public String getAlias() { + return this.alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } +} diff --git a/src/main/java/com/midm/model/store/StoreWebApp.java b/src/main/java/com/midm/model/store/StoreWebApp.java new file mode 100644 index 0000000..839e3f9 --- /dev/null +++ b/src/main/java/com/midm/model/store/StoreWebApp.java @@ -0,0 +1,216 @@ +package com.midm.model.store; + +import com.google.common.base.Strings; +import com.midm.model.file.BaseFile; +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McFile; +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.Enumeration; +import java.util.List; +import java.util.Properties; +import java.util.UUID; +import java.util.jar.JarFile; +import java.util.zip.ZipEntry; +import org.joda.time.DateTime; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class StoreWebApp extends BaseFile { + private DbObject appInfo; + private Boolean isFormal; + private List releaseNote; + private List releaseNoteNewFunction; + + public StoreWebApp() { + } + + public StoreWebApp(User user, UUID fileUuid, McFile file) { + super(user, fileUuid, file); + this.setAppInfo((File)file); + } + + public StoreWebApp(McFile file) { + super((User)null, (UUID)null, file); + this.setAppInfo((File)file); + } + + public boolean isFormal() { + return this.isFormal != null && this.isFormal; + } + + public void setIsFormal(boolean isFormal) { + this.isFormal = isFormal; + } + + public DbObject getAppInfo() { + if (this.appInfo == null) { + this.appInfo = new DbObject(); + } + + return this.appInfo; + } + + public void setAppInfo(DbObject appInfo) { + this.appInfo = appInfo; + } + + public void setAppInfo(String key, Object value) { + if (!this.getAppInfo().containsKey(key)) { + this.getAppInfo().append(key, value); + } + + } + + public void setAppInfo(Properties properties) { + properties.forEach((key, value) -> { + String name = (String)key; + if (name.startsWith("build")) { + name = name.substring(6); + } + + switch (name) { + case "build.group": + case "group": + case "groupId": + this.setAppInfo("groupId", value); + break; + case "build.artifact": + case "artifact": + case "artifactId": + this.setAppInfo("artifactId", value); + break; + case "build.name": + case "name": + case "m2e.projectName": + this.setName((String)value); + break; + case "build.time": + case "time": + this.setAppInfo("buildTime", DateTime.parse((String)value).toDate()); + break; + case "build.version": + case "version": + this.setAppInfo("version", value); + } + + }); + } + + public String getGroupId() { + return this.getAppInfo().getString("groupId"); + } + + public String getArtifactId() { + return this.getAppInfo().getString("artifactId"); + } + + public String getVersion() { + return this.getAppInfo().getString("version"); + } + + public Date getBuildTime() { + return this.getAppInfo().getDate("buildTime"); + } + + public List getReleaseNote() { + if (this.releaseNote == null) { + this.releaseNote = new ArrayList(); + } + + return this.releaseNote; + } + + public void setReleaseNote(List releaseNote) { + this.releaseNote = releaseNote; + } + + public boolean hasReleaseNote() { + return !this.getReleaseNote().isEmpty(); + } + + public List getReleaseNoteNewFunction() { + if (this.releaseNoteNewFunction == null) { + this.releaseNoteNewFunction = new ArrayList(); + } + + return this.releaseNoteNewFunction; + } + + public void setReleaseNoteNewFunction(List releaseNoteNewFunction) { + this.releaseNoteNewFunction = releaseNoteNewFunction; + } + + public boolean hasReleaseNoteNewFunction() { + return !this.getReleaseNoteNewFunction().isEmpty(); + } + + public boolean isWebApp() { + return !Strings.isNullOrEmpty(this.getGroupId()) && !Strings.isNullOrEmpty(this.getArtifactId()); + } + + public String getFileName() { + String fileName = super.getFileName(); + if (Strings.isNullOrEmpty(fileName)) { + fileName = String.format("%s.%s.war", this.getName(), this.getVersion()); + } + + return fileName; + } + + private void setAppInfo(File file) { + try { + JarFile jarFile = new JarFile(file); + + try { + ZipEntry entry = this.findZipEntry(jarFile, "build-info.properties"); + if (entry != null) { + Properties properties = new Properties(); + properties.load(jarFile.getInputStream(entry)); + this.setAppInfo(properties); + } + + entry = this.findZipEntry(jarFile, "pom.properties"); + if (entry != null) { + Properties properties = new Properties(); + properties.load(jarFile.getInputStream(entry)); + this.setAppInfo(properties); + } + + entry = this.findZipEntry(jarFile, "project.properties"); + if (entry != null) { + Properties properties = new Properties(); + properties.load(jarFile.getInputStream(entry)); + this.setAppInfo(properties); + } + } catch (Throwable var6) { + try { + jarFile.close(); + } catch (Throwable var5) { + var6.addSuppressed(var5); + } + + throw var6; + } + + jarFile.close(); + } catch (Exception var7) { + } + + } + + private ZipEntry findZipEntry(JarFile jarFile, String name) { + Enumeration entries = jarFile.entries(); + + while(entries.hasMoreElements()) { + ZipEntry entry = (ZipEntry)entries.nextElement(); + if (entry.getName().endsWith(name)) { + return entry; + } + } + + return null; + } +} diff --git a/src/main/java/com/midm/model/system/AltLocale.java b/src/main/java/com/midm/model/system/AltLocale.java new file mode 100644 index 0000000..888adb8 --- /dev/null +++ b/src/main/java/com/midm/model/system/AltLocale.java @@ -0,0 +1,32 @@ +package com.midm.model.system; + +import java.util.Locale; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class AltLocale { + @Id + private String locale; + private String altLocale; + + public String getLocale() { + return this.locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } + + public String getAltLocale() { + return this.altLocale; + } + + public void setAltLocale(String altLocale) { + this.altLocale = altLocale; + } + + public Locale toLocale() { + return Locale.forLanguageTag(this.getAltLocale()); + } +} diff --git a/src/main/java/com/midm/model/system/Category.java b/src/main/java/com/midm/model/system/Category.java new file mode 100644 index 0000000..67609ea --- /dev/null +++ b/src/main/java/com/midm/model/system/Category.java @@ -0,0 +1,94 @@ +package com.midm.model.system; + +import com.mitac.cell.db.DbObject; +import java.util.List; +import java.util.Locale; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class Category { + @Id + public CategoryId id; + public int order; + public DbObject profile; + public List features; + + public Category() { + } + + public Category(String use, String categoryId) { + this.id = new CategoryId(use, categoryId); + } + + public CategoryId getId() { + if (this.id == null) { + this.id = new CategoryId(); + } + + return this.id; + } + + public void setId(CategoryId id) { + this.id = id; + } + + public String getUse() { + return this.getId().getUse(); + } + + public void setUse(String use) { + this.getId().setUse(use); + } + + public String getCategoryId() { + return this.getId().getId(); + } + + public void setCategoryId(String id) { + this.getId().setId(id); + } + + public void setCategory(String use, String categoryId) { + this.getId().set(use, categoryId); + } + + public List getFeatures() { + return this.features; + } + + public void setFeatures(List features) { + this.features = features; + } + + public int getOrder() { + return this.order; + } + + public void setOrder(int order) { + this.order = order; + } + + public DbObject getProfile() { + if (this.profile == null) { + this.profile = new DbObject(); + } + + return this.profile; + } + + public void setProfile(DbObject profile) { + this.profile = profile; + } + + public void setProfile(Locale locale, String name, String desc) { + DbObject profile = new DbObject(); + profile.put("name", name); + profile.put("desc", desc); + this.getProfile().put(locale.toString(), profile); + } + + public DbObject getProfile(Locale locale) { + return (DbObject)this.getProfile().get(locale.toString()); + } +} diff --git a/src/main/java/com/midm/model/system/CategoryId.java b/src/main/java/com/midm/model/system/CategoryId.java new file mode 100644 index 0000000..3f96a57 --- /dev/null +++ b/src/main/java/com/midm/model/system/CategoryId.java @@ -0,0 +1,36 @@ +package com.midm.model.system; + +import java.io.Serializable; + +public class CategoryId implements Serializable { + private String use; + private String id; + + public CategoryId() { + } + + public CategoryId(String use, String id) { + this.set(use, id); + } + + public String getUse() { + return this.use; + } + + public void setUse(String use) { + this.use = use; + } + + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + public void set(String use, String id) { + this.setUse(use); + this.setId(id); + } +} diff --git a/src/main/java/com/midm/model/system/DbTemplate.java b/src/main/java/com/midm/model/system/DbTemplate.java new file mode 100644 index 0000000..db7380b --- /dev/null +++ b/src/main/java/com/midm/model/system/DbTemplate.java @@ -0,0 +1,54 @@ +package com.midm.model.system; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class DbTemplate { + @Id + private String code; + private String name; + private String content; + private String comment; + + public DbTemplate() { + } + + public DbTemplate(String code, String name, String content) { + this.setCode(code); + this.setName(name); + this.setContent(content); + } + + public String getCode() { + return this.code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getContent() { + return this.content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getComment() { + return this.comment; + } + + public void setComment(String comment) { + this.comment = comment; + } +} diff --git a/src/main/java/com/midm/model/system/HelpMessage.java b/src/main/java/com/midm/model/system/HelpMessage.java new file mode 100644 index 0000000..0fed051 --- /dev/null +++ b/src/main/java/com/midm/model/system/HelpMessage.java @@ -0,0 +1,102 @@ +package com.midm.model.system; + +import com.google.common.base.Strings; +import com.mitac.cell.db.DbObject; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class HelpMessage { + @Id + private String code; + private DbObject message; + private DbObject options; + private String comment; + + public HelpMessage() { + } + + public HelpMessage(String code) { + this.setCode(code); + } + + public HelpMessage(String code, String locale, String title, String desc, String comment) { + this.setCode(code); + this.setMessage(locale, title, desc); + this.setComment(comment); + } + + public String getCode() { + return this.code; + } + + public void setCode(String code) { + this.code = code; + } + + public DbObject getMessage() { + if (this.message == null) { + this.message = new DbObject(); + } + + return this.message; + } + + public void setMessages(DbObject messages) { + this.message = messages; + } + + public void setMessage(String locale, String title, String desc) { + this.getMessage().append(locale, (new DbObject("title", title)).append("desc", this.message)); + } + + public String getTitle(String locale) { + return this.getMessage(locale).getString("title"); + } + + public DbObject getMessage(String locale) { + return this.getMessage().getDbObject(new String[]{Strings.isNullOrEmpty(locale) ? "en-US" : locale}); + } + + public String getDescription(String locale) { + return this.getMessage(locale).getString("desc"); + } + + public DbObject getOptions() { + if (this.options == null) { + this.options = new DbObject(); + } + + return this.options; + } + + public DbObject getOptions(String category) { + Object categoryObject = this.getOptions().get(category); + if (categoryObject == null) { + categoryObject = new DbObject(); + this.getOptions().put(category, categoryObject); + } + + return (DbObject)categoryObject; + } + + public void setOptions(DbObject options) { + this.options = options; + } + + public void setOptions(String category, DbObject options) { + this.getOptions().put(category, options); + } + + public void setOptions(String category, String key, String desc) { + this.getOptions(category).put(key, desc); + } + + public String getComment() { + return this.comment; + } + + public void setComment(String comment) { + this.comment = comment; + } +} diff --git a/src/main/java/com/midm/model/system/HostLicense.java b/src/main/java/com/midm/model/system/HostLicense.java new file mode 100644 index 0000000..594b645 --- /dev/null +++ b/src/main/java/com/midm/model/system/HostLicense.java @@ -0,0 +1,355 @@ +package com.midm.model.system; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.net.McNetUtils; +import com.mitac.cell.security.McTextEncryptor; +import com.mitac.cell.system.McSystemInfo; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import org.joda.time.DateTime; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class HostLicense { + public static final Integer trialPeriod = 45; + private static final Integer trialDeviceLimit = -1; + private static final Integer trialSiteLimit = -1; + @Transient + private String hostId; + @Transient + private Integer siteLimit; + @Transient + private Integer deviceLimit; + @Transient + private Long validFrom; + @Transient + private Long validTo; + @Transient + private boolean isStandalone; + @Transient + private Boolean isValidKey; + @Id + private String systemHash; + private String licenseKey; + private DbObject properties; + private boolean isPrimary; + @Expose( + serialize = false + ) + private String validated; + @Transient + private Long validatedAt; + @Transient + @Expose( + serialize = false + ) + private McTextEncryptor encryptor; + private static final String tokenPassword = "MiDM@MiTAC.com"; + private static final String tokenSalt = "171891893b5cef2f"; + public static final McTextEncryptor sourceEncryptor = new McTextEncryptor("MiDM@MiTAC.com", "171891893b5cef2f"); + + public HostLicense() { + this.siteLimit = trialSiteLimit; + this.deviceLimit = trialDeviceLimit; + this.validFrom = -1L; + this.validTo = -1L; + this.isStandalone = false; + this.isValidKey = false; + } + + public HostLicense(String hostId, String systemHash) { + this(hostId, systemHash, (String)null); + } + + public HostLicense(String hostId, String systemHash, String licenseKey) { + this.siteLimit = trialSiteLimit; + this.deviceLimit = trialDeviceLimit; + this.validFrom = -1L; + this.validTo = -1L; + this.isStandalone = false; + this.isValidKey = false; + this.hostId = hostId; + this.setSystemHash(systemHash); + this.setLicenseKey(licenseKey); + this.dispatch(); + } + + public String getSystemHash() { + return this.systemHash; + } + + public void setSystemHash(String systemHash) { + this.systemHash = systemHash; + } + + public String getHostId() { + return this.hostId; + } + + public void setHostId(String hostId) { + this.hostId = hostId; + this.refreshEncryptor(); + } + + private void refreshEncryptor() { + if (!Strings.isNullOrEmpty(this.hostId) && !Strings.isNullOrEmpty(this.systemHash)) { + try { + this.encryptor = new McTextEncryptor(this.hostId, this.systemHash); + } catch (Exception var2) { + this.encryptor = null; + } + } else { + this.encryptor = null; + } + + } + + public String getLicenseKey() { + return this.licenseKey; + } + + public boolean hasLicenseKey() { + return !Strings.isNullOrEmpty(this.licenseKey); + } + + public void setLicenseKey(String licenseKey) { + this.licenseKey = licenseKey; + if (Strings.isNullOrEmpty(licenseKey)) { + this.siteLimit = trialSiteLimit; + this.deviceLimit = trialDeviceLimit; + } else { + this.dispatch(licenseKey); + } + + } + + public boolean isValidKey() { + return this.isValidKey; + } + + public int getSiteLimit() { + return this.siteLimit; + } + + public void setSiteLimit(int siteLimit) { + this.siteLimit = siteLimit; + } + + public int getDeviceLimit() { + return this.deviceLimit; + } + + public void setDeviceLimit(int deviceLimit) { + this.deviceLimit = deviceLimit; + } + + public Long getValidFrom() { + return this.validFrom; + } + + public void setValidFrom(Long validFrom) { + this.validFrom = validFrom; + } + + public Long getValidTo() { + return this.validTo; + } + + public void setValidTo(Long validTo) { + this.validTo = validTo; + } + + public boolean isStandalone() { + return this.isStandalone; + } + + public void setIsStandalone(boolean isStandalone) { + this.isStandalone = isStandalone; + } + + public void setAsTrial() { + this.setIsStandalone(true); + this.setDeviceLimit(trialDeviceLimit); + if (this.validFrom == null) { + this.validFrom = (new Date()).getTime(); + } + + this.validTo = (new DateTime(this.validFrom)).plusDays(trialPeriod).getMillis(); + } + + public boolean isValid() { + return !this.isExpired() && this.isValidated(); + } + + private boolean isValidated() { + return DateTime.now().isBefore((new DateTime(this.validatedDate())).plusDays(trialPeriod)); + } + + private boolean isExpired() { + return this.validTo != -1L && (new DateTime(this.validTo)).plusDays(1).isBeforeNow(); + } + + public DbObject getProperties() { + if (this.properties == null) { + this.properties = new DbObject(); + } + + return this.properties; + } + + public void setProperties(DbObject properties) { + this.properties = properties; + } + + public void setProperty(String key, String value) { + this.getProperties().append(key, value); + } + + public void dispatch() { + if (!Strings.isNullOrEmpty(this.getLicenseKey())) { + this.dispatch(this.getLicenseKey()); + } + + this.validatedDate(); + } + + public void validate() { + this.setProperty("ip_addr", McNetUtils.getIpAddress()); + this.setProperty("host_name", McNetUtils.hostName()); + if (this.encryptor != null) { + this.validated = this.encryptor.encrypt(String.valueOf((new Date()).getTime())); + } + + } + + public Long validatedDate() { + this.validatedAt = null; + if (!Strings.isNullOrEmpty(this.validated)) { + String dateString = this.encryptor.decrypt(this.validated); + if (!Strings.isNullOrEmpty(dateString)) { + this.validatedAt = Long.parseLong(dateString); + } + } + + return this.validatedAt; + } + + public boolean isPrimary() { + return this.isPrimary; + } + + public void setPrimary(boolean isPrimary) { + this.isPrimary = isPrimary; + } + + public void dispatch(String encryptedLicense) { + if (this.encryptor == null) { + this.refreshEncryptor(); + } + + if (this.encryptor != null && !Strings.isNullOrEmpty(encryptedLicense)) { + try { + String license = this.encryptor.decrypt(encryptedLicense); + if (!Strings.isNullOrEmpty(license)) { + JsonObject jLicense = McJsonUtils.toJsonElement(license).getAsJsonObject(); + this.setDeviceLimit(McJsonUtils.getInt(jLicense, "deviceLimit", -1)); + this.setValidTo(McJsonUtils.getLong(jLicense, "validTo", -1L)); + this.setIsStandalone(McJsonUtils.getInt(jLicense, "isStandalone", -1) > 0); + this.isValidKey = true; + return; + } + } catch (Exception var4) { + } + + this.setAsTrial(); + this.isValidKey = false; + } else { + this.setAsTrial(); + } + } + + public static String generateSystemHash(String systemHash) { + if (!Strings.isNullOrEmpty(systemHash)) { + return systemHash; + } else { + McSystemInfo systemInfo = new McSystemInfo(); + List macAddresses = systemInfo.getMacAddresses(); + if (macAddresses != null && !macAddresses.isEmpty()) { + ByteBuffer bb = ByteBuffer.allocate(macAddresses.size() * 6); + + for(byte[] macAddr : macAddresses) { + bb.put(macAddr); + } + + byte[] macBytes = bb.array(); + Arrays.sort(macBytes); + + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + return McStringUtils.toHexString(md.digest(macBytes)); + } catch (NoSuchAlgorithmException var6) { + } + } + + return null; + } + } + + public static String encrypt(String value) { + return sourceEncryptor.encrypt(value); + } + + public static String decrypt(String value) { + return sourceEncryptor.decrypt(value); + } + + public String generateLicense() { + String licenseKey = this.generateLicense(this.siteLimit, this.deviceLimit, this.validTo, false, this.isStandalone); + this.setLicenseKey(licenseKey); + return licenseKey; + } + + public String generateLicense(Integer siteLimit, Integer deviceLimit, Long validTo, Boolean isLicenseServer, Boolean isStandalone) { + if (this.encryptor == null) { + this.refreshEncryptor(); + } + + if (this.encryptor == null) { + return null; + } else { + JsonObject jLicense = new JsonObject(); + if (siteLimit != null && siteLimit > 0) { + jLicense.addProperty("siteLimit", siteLimit); + } + + if (deviceLimit != null && deviceLimit > 0) { + jLicense.addProperty("deviceLimit", deviceLimit); + } + + if (validTo != null && validTo > 0L) { + jLicense.addProperty("validTo", validTo); + } + + if (isLicenseServer != null && isLicenseServer) { + jLicense.addProperty("isLicenseServer", 1); + } + + if (isStandalone != null && isStandalone) { + jLicense.addProperty("isStandalone", 1); + } + + return this.encryptor.encrypt(jLicense.toString()); + } + } +} diff --git a/src/main/java/com/midm/model/system/LicenseFeature.java b/src/main/java/com/midm/model/system/LicenseFeature.java new file mode 100644 index 0000000..690c4d8 --- /dev/null +++ b/src/main/java/com/midm/model/system/LicenseFeature.java @@ -0,0 +1,53 @@ +package com.midm.model.system; + +import com.mitac.cell.db.DbObject; +import java.util.Locale; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class LicenseFeature { + @Id + String code; + CategoryId categoryId; + DbObject profile; + + public String getCode() { + return this.code; + } + + public void setCode(String code) { + this.code = code; + } + + public CategoryId getCategoryId() { + return this.categoryId; + } + + public void setCategoryId(CategoryId categoryId) { + this.categoryId = categoryId; + } + + public DbObject getProfile() { + if (this.profile == null) { + this.profile = new DbObject(); + } + + return this.profile; + } + + public void setProfile(DbObject profile) { + this.profile = profile; + } + + public void setProfile(Locale locale, String name, String desc) { + DbObject profile = new DbObject(); + profile.put("name", name); + profile.put("desc", desc); + this.getProfile().put(locale.toString(), profile); + } + + public DbObject getProfile(Locale locale) { + return (DbObject)this.getProfile().get(locale.toString()); + } +} diff --git a/src/main/java/com/midm/model/system/LicenseModel.java b/src/main/java/com/midm/model/system/LicenseModel.java new file mode 100644 index 0000000..e4761b8 --- /dev/null +++ b/src/main/java/com/midm/model/system/LicenseModel.java @@ -0,0 +1,269 @@ +package com.midm.model.system; + +import com.google.common.base.Strings; +import com.mitac.cell.db.DbObject; +import java.util.Date; +import java.util.UUID; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class LicenseModel { + public static final char TYPE_TRIAL = 't'; + public static final char TYPE_PERPETUAL = 'p'; + public static final char TYPE_YEARLY = 'y'; + public static final char TYPE_MONTHLY = 'm'; + public static final char TYPE_DAILY = 'd'; + public static final int DEFAULT_TRIAL_DAYS = 45; + @Id + private UUID uuid; + private String name; + private String idName; + private DbObject profile; + private Character type; + private Integer period; + private String freshExpiry; + private String activatedExpiry; + private String autoExtend; + private Integer maxActivation = 2; + private boolean isFormal; + @Transient + private DbObject report; + + public LicenseModel() { + } + + public LicenseModel(String name, Character type, Integer period, Integer maxActivation) { + this.initUuid(); + this.name = name; + this.type = type; + this.period = period; + this.maxActivation = maxActivation; + } + + public void initUuid() { + this.setUuid(UUID.randomUUID()); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIdName() { + return this.idName; + } + + public void setIdName(String idName) { + this.idName = idName; + } + + public Integer getPeriod() { + return this.period; + } + + public void setPeriod(int period) { + this.period = period; + } + + public Character getType() { + return this.type; + } + + public void setType(char type) { + this.type = type; + } + + public boolean isTrial() { + return this.getType() == 't'; + } + + public boolean isPerpetual() { + return this.getType() == 'p'; + } + + public Integer getMaxActivation() { + return this.maxActivation; + } + + public void setMaxActivation(int maxCount) { + this.maxActivation = maxCount; + } + + public DbObject getProfile() { + return this.profile; + } + + public boolean isFormal() { + return this.isFormal; + } + + public void setFormal(boolean isFormal) { + this.isFormal = isFormal; + } + + public void setProfile(DbObject profile) { + this.profile = profile; + } + + public DbObject getReport() { + if (this.report == null) { + this.report = new DbObject(); + } + + return this.report; + } + + public long getReportAsLong(String key) { + return this.getReport().getLong(key); + } + + public void setReport(DbObject report) { + this.report = report; + } + + public void setReport(String key, Object data) { + this.getReport().put(key, data); + } + + public String getFreshExpiry() { + if (Strings.isNullOrEmpty(this.freshExpiry)) { + switch (this.getType()) { + case 'p': + case 'y': + this.freshExpiry = "6m"; + break; + case 't': + this.freshExpiry = "45d"; + break; + default: + String var10001 = String.valueOf(this.period); + this.freshExpiry = var10001 + this.type; + } + } + + return this.freshExpiry; + } + + public void setFreshExpiry(String expiry) { + this.freshExpiry = expiry; + } + + public String getActivatedExpiry() { + if (Strings.isNullOrEmpty(this.activatedExpiry)) { + switch (this.getType()) { + case 'p': + this.activatedExpiry = "3y"; + break; + case 't': + this.activatedExpiry = "45d"; + break; + default: + String var10001 = String.valueOf(this.period); + this.activatedExpiry = var10001 + this.type; + } + } + + return this.activatedExpiry; + } + + public void setActivatedExpiry(String expiry) { + this.activatedExpiry = expiry; + } + + public String getAutoExtend() { + if (this.isPerpetual()) { + this.autoExtend = "1y"; + } + + return this.autoExtend; + } + + public void setAutoExtend(String extend) { + this.autoExtend = extend; + } + + public Date getFreshExpiry(Date from) { + return (new Period(this.getFreshExpiry())).from(from); + } + + public Date getActivatedExpiry(Date from) { + return (new Period(this.getActivatedExpiry())).from(from); + } + + public Date getNextExpiry(Date from) { + return (new Period(this.getAutoExtend())).from(from); + } + + public static LicenseModel defaultTrial() { + return new LicenseModel("Trial", 't', 45, 45); + } + + public class Period { + private int period = 0; + private char unit = 'd'; + + public Period(int period, char unit) { + this.period = period; + this.unit = unit; + } + + public Period(String expireBy) { + if (!Strings.isNullOrEmpty(expireBy)) { + String[] tokens = expireBy.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); + this.period = Integer.parseInt(tokens[0]); + this.unit = tokens[1].toLowerCase().charAt(0); + } + + } + + public int getPeriod() { + return this.period; + } + + public char getUnit() { + return this.unit; + } + + public Date fromNow() { + return this.from(new Date()); + } + + public Date from(Date date) { + if (this.period > 0) { + LocalDate localDate = (new DateTime(date)).plusDays(1).toLocalDate(); + switch (this.unit) { + case 'd': + case 't': + return localDate.plusDays(this.period).toDate(); + case 'm': + return localDate.plusMonths(this.period).toDate(); + case 'y': + return localDate.plusYears(this.period).toDate(); + default: + return null; + } + } else { + return null; + } + } + + public String toString() { + return "" + this.period + this.unit; + } + } +} diff --git a/src/main/java/com/midm/model/system/PolicyAgreement.java b/src/main/java/com/midm/model/system/PolicyAgreement.java new file mode 100644 index 0000000..dd5b317 --- /dev/null +++ b/src/main/java/com/midm/model/system/PolicyAgreement.java @@ -0,0 +1,99 @@ +package com.midm.model.system; + +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import java.util.Date; +import java.util.Locale; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class PolicyAgreement { + @Id + private UUID uuid; + @DBRef + private User writer; + private String category; + private String version; + private DbObject message; + private Date created; + + public PolicyAgreement() { + this.init(); + } + + public void init() { + this.uuid = UUID.randomUUID(); + this.created = new Date(); + } + + public UUID getUuid() { + return this.uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public User getWriter() { + return this.writer; + } + + public void setWriter(User writer) { + this.writer = writer; + } + + public String getCategory() { + return this.category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public String getVersion() { + return this.version; + } + + public void setVersion(String version) { + this.version = version; + } + + public DbObject getMessage() { + if (this.message == null) { + this.message = new DbObject(); + } + + return this.message; + } + + public String getContent() { + return this.message.getString("content"); + } + + public void setContent(String content) { + this.setContent(Locale.US.toLanguageTag(), content); + } + + public void setContent(String languageTag, String content) { + DbObject message = this.getMessage(languageTag); + message.put("content", content); + } + + public DbObject getMessage(String languageTag) { + DbObject message = this.getMessage(); + DbObject localedMessage = new DbObject(); + message.put(languageTag, localedMessage); + return localedMessage; + } +} diff --git a/src/main/java/com/midm/model/system/ResourceLocale.java b/src/main/java/com/midm/model/system/ResourceLocale.java new file mode 100644 index 0000000..4c555ad --- /dev/null +++ b/src/main/java/com/midm/model/system/ResourceLocale.java @@ -0,0 +1,68 @@ +package com.midm.model.system; + +import java.util.Locale; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class ResourceLocale { + @Id + private String locale; + private String name; + private Integer order; + private Boolean enabled; + + public ResourceLocale() { + } + + public ResourceLocale(String locale, String name) { + this.init(locale, name, true); + } + + public ResourceLocale(String locale, String name, boolean enabled) { + this.init(locale, name, enabled); + } + + public void init(String locale, String name, boolean enabled) { + this.setLocale(locale); + this.setName(name); + this.setEnabled(enabled); + this.setOrder(0); + } + + public String getLocale() { + return this.locale; + } + + public void setLocale(String locale) { + this.locale = locale; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean isEnabled() { + return this.enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + public Integer getOrder() { + return this.order; + } + + public void setOrder(Integer order) { + this.order = order; + } + + public Locale toLocale() { + return Locale.forLanguageTag(this.getLocale()); + } +} diff --git a/src/main/java/com/midm/model/system/ResourceMessage.java b/src/main/java/com/midm/model/system/ResourceMessage.java new file mode 100644 index 0000000..77cb1a7 --- /dev/null +++ b/src/main/java/com/midm/model/system/ResourceMessage.java @@ -0,0 +1,68 @@ +package com.midm.model.system; + +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McStringUtils; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class ResourceMessage { + @Id + private String code; + private DbObject messages; + private String comment; + + public ResourceMessage() { + } + + public ResourceMessage(String code) { + this.setCode(code); + } + + public ResourceMessage(String code, String locale, String message, String comment) { + this.setCode(code); + this.setMessage(locale, message); + this.setComment(comment); + } + + public String getCode() { + return this.code; + } + + public void setCode(String code) { + this.code = code; + } + + public DbObject getMessages() { + if (this.messages == null) { + this.messages = new DbObject(); + } + + return this.messages; + } + + public void setMessages(DbObject messages) { + this.messages = messages; + } + + public void setMessage(String locale, String message) { + this.getMessages().append(locale, message); + } + + public String getMessage(String locale) { + String message = this.getMessages().getString(locale); + return McStringUtils.isNullOrEmpty(message) ? getDefaultMessage(this.code) : message; + } + + public static String getDefaultMessage(String code) { + return "#" + code; + } + + public String getComment() { + return this.comment; + } + + public void setComment(String comment) { + this.comment = comment; + } +} diff --git a/src/main/java/com/midm/model/system/StandaloneLicense.java b/src/main/java/com/midm/model/system/StandaloneLicense.java new file mode 100644 index 0000000..3ec4ce2 --- /dev/null +++ b/src/main/java/com/midm/model/system/StandaloneLicense.java @@ -0,0 +1,218 @@ +package com.midm.model.system; + +import com.google.common.base.CharMatcher; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.DBRef; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class StandaloneLicense { + @Id + private UUID uuid; + @DBRef + private Site site; + private User writer; + private String hostId; + private String systemHash; + private String licenseType; + private String licenseKey; + private String status; + private Integer deviceLimit; + private long validTo = -1L; + private Integer period; + private boolean isStandalone = true; + private List notes; + private Date updated; + protected Date created; + + public UUID getUuid() { + return this.uuid; + } + + public void init(User user) { + this.uuid = UUID.randomUUID(); + this.writer = user; + this.created = new Date(); + this.updated = new Date(); + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public String getHostId() { + return this.hostId; + } + + public void setHostId(String hostId) { + this.hostId = hostId; + } + + public String getSystemHash() { + return this.systemHash; + } + + public void setSystemHash(String systemHash) { + this.systemHash = systemHash; + } + + public String getLicenseKey() { + return this.licenseKey; + } + + public void setLicenseKey(String licenseKey) { + this.licenseKey = licenseKey; + } + + public Integer getDeviceLimit() { + return this.deviceLimit; + } + + public void setDeviceLimit(Integer deviceLimit) { + this.deviceLimit = deviceLimit; + } + + public long getValidTo() { + return this.validTo; + } + + public void setValidTo(long validTo) { + this.validTo = validTo; + } + + public boolean isStandalone() { + return this.isStandalone; + } + + public void setStandalone(boolean isStandalone) { + this.isStandalone = isStandalone; + } + + public Site getSite() { + return this.site; + } + + public void setSite(Site site) { + this.site = site; + } + + public String getLicenseType() { + return this.licenseType; + } + + public void setLicenseType(String licenseType) { + this.licenseType = licenseType; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getUpdated() { + return this.updated; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } + + public List getNotes() { + if (this.notes == null) { + this.notes = new ArrayList(); + } + + return this.notes; + } + + public void setNotes(List notes) { + this.notes = notes; + } + + public void addNote(String note) { + this.getNotes().add(new Note(this.writer, note)); + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Integer getPeriod() { + return this.period; + } + + public void setPeriod(Integer period) { + this.period = period; + } + + public static enum STATUS { + REQUESTED, + PROCESSING, + CONFIRMED, + CANCELED, + REJECTED, + EXPIRED, + RENEWED, + UNKNOWN; + + public static STATUS get(String key) { + try { + return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); + } catch (Exception var2) { + return UNKNOWN; + } + } + } + + public static class Note { + private User recordedBy; + private String note; + private Date noted; + + public Note() { + } + + public Note(User user, String note) { + this.recordedBy = user; + this.note = note; + this.noted = new Date(); + } + + public User getRecordedBy() { + return this.recordedBy; + } + + public void setRecordedBy(User recordedBy) { + this.recordedBy = recordedBy; + } + + public String getNote() { + return this.note; + } + + public void setNote(String note) { + this.note = note; + } + + public Date getNoted() { + return this.noted; + } + + public void setNoted(Date noted) { + this.noted = noted; + } + } +} diff --git a/src/main/java/com/midm/model/system/SystemSetting.java b/src/main/java/com/midm/model/system/SystemSetting.java new file mode 100644 index 0000000..c6ac679 --- /dev/null +++ b/src/main/java/com/midm/model/system/SystemSetting.java @@ -0,0 +1,48 @@ +package com.midm.model.system; + +import com.mitac.cell.utils.McNumberUtils; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class SystemSetting { + @Id + private String key; + private String value; + + public SystemSetting() { + } + + public SystemSetting(String key, Object value) { + this.setKey(key); + this.setValue(value != null ? String.valueOf(value) : null); + } + + public String getKey() { + return this.key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public Integer getAsInteger() { + return McNumberUtils.toInt(this.getValue()); + } + + public Long getAsLong() { + return McNumberUtils.toLong(this.getValue()); + } + + public Boolean getAsBoolean() { + return this.value.equalsIgnoreCase("true"); + } +} diff --git a/src/main/java/com/midm/model/template/MailTemplate.java b/src/main/java/com/midm/model/template/MailTemplate.java new file mode 100644 index 0000000..b76d47b --- /dev/null +++ b/src/main/java/com/midm/model/template/MailTemplate.java @@ -0,0 +1,80 @@ +package com.midm.model.template; + +import com.midm.model.org.User; +import com.mitac.cell.db.DbObject; +import java.util.Date; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +public class MailTemplate { + @Id + private String idName; + private String name; + private String description; + private DbObject template; + private User writer; + private Date created; + private Date updated; + + public void init() { + this.created = new Date(); + this.updated = new Date(); + } + + public String getIdName() { + return this.idName; + } + + public void setIdName(String idName) { + this.idName = idName; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public DbObject getTemplate() { + return this.template; + } + + public void setTemplate(DbObject template) { + this.template = template; + } + + public User getWriter() { + return this.writer; + } + + public void setWriter(User writer) { + this.writer = writer; + } + + public Date getCreated() { + return this.created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getUpdated() { + return this.updated; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } +} diff --git a/src/main/java/com/midm/repository/device/DeviceLicenseRepository.java b/src/main/java/com/midm/repository/device/DeviceLicenseRepository.java new file mode 100644 index 0000000..b615167 --- /dev/null +++ b/src/main/java/com/midm/repository/device/DeviceLicenseRepository.java @@ -0,0 +1,6 @@ +package com.midm.repository.device; + +import org.springframework.data.mongodb.repository.MongoRepository; + +public interface DeviceLicenseRepository extends MongoRepository { +} diff --git a/src/main/java/com/midm/resolver/DbResourceResolver.java b/src/main/java/com/midm/resolver/DbResourceResolver.java new file mode 100644 index 0000000..bfbfee8 --- /dev/null +++ b/src/main/java/com/midm/resolver/DbResourceResolver.java @@ -0,0 +1,4 @@ +package com.midm.resolver; + +public class DbResourceResolver { +} diff --git a/src/main/java/com/midm/resolver/DbTemplateResolver.java b/src/main/java/com/midm/resolver/DbTemplateResolver.java new file mode 100644 index 0000000..0f9b5b2 --- /dev/null +++ b/src/main/java/com/midm/resolver/DbTemplateResolver.java @@ -0,0 +1,15 @@ +package com.midm.resolver; + +import com.google.common.collect.Sets; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.templatemode.TemplateMode; + +public class DbTemplateResolver extends SpringResourceTemplateResolver { + private static final String PREFIX = "dbTemplate:"; + + public DbTemplateResolver() { + this.setTemplateMode(TemplateMode.HTML); + this.setCacheable(true); + this.setResolvablePatterns(Sets.newHashSet(new String[]{"dbTemplate:*"})); + } +} diff --git a/src/main/java/com/midm/security/UserPrincipal.java b/src/main/java/com/midm/security/UserPrincipal.java new file mode 100644 index 0000000..79babc7 --- /dev/null +++ b/src/main/java/com/midm/security/UserPrincipal.java @@ -0,0 +1,45 @@ +package com.midm.security; + +import com.midm.model.org.User; +import com.midm.model.org.UserToken; +import java.io.Serializable; +import java.security.Principal; +import java.util.UUID; +import org.springframework.security.core.Authentication; +import org.springframework.web.socket.WebSocketSession; + +public class UserPrincipal implements Principal, Serializable { + private User user; + + public UserPrincipal(User user) { + this.setUser(user); + } + + public UUID getUserUuid() { + return this.user == null ? null : this.user.getUuid(); + } + + public String getName() { + return this.user == null ? null : this.user.getUuid().toString(); + } + + public User getUser() { + return this.user; + } + + public void setUser(User user) { + this.user = user; + } + + public static User getUser(Authentication authentication) { + return authentication == null ? null : ((UserPrincipal)authentication.getPrincipal()).getUser(); + } + + public static User getUser(WebSocketSession session) { + return getUser((Authentication)session.getPrincipal()); + } + + public static UserToken getUserToken(Authentication authentication) { + return authentication == null ? null : (UserToken)authentication.getCredentials(); + } +} diff --git a/src/main/java/com/midm/service/Aggregations.java b/src/main/java/com/midm/service/Aggregations.java new file mode 100644 index 0000000..195484f --- /dev/null +++ b/src/main/java/com/midm/service/Aggregations.java @@ -0,0 +1,69 @@ +package com.midm.service; + +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.List; +import org.bson.Document; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext; + +public class Aggregations { + public static AggregationOperation newOperation(Document operation) { + return new CustomOperation(operation); + } + + public static AggregationOperation newOperation(String jOperation) { + return new CustomOperation(jOperation); + } + + public static AggregationOperation newOperation(JsonObject jOperation) { + return new CustomOperation(Document.parse(jOperation.toString())); + } + + public static Aggregation from(String... jOperations) { + List operations = new ArrayList(); + + for(String operation : jOperations) { + operations.add(new CustomOperation(operation)); + } + + return Aggregation.newAggregation(operations); + } + + public static Aggregation from(Document... documents) { + List operations = new ArrayList(); + + for(Document document : documents) { + operations.add(new CustomOperation(document)); + } + + return Aggregation.newAggregation(operations); + } + + public static Aggregation from(List documents) { + List operations = new ArrayList(); + + for(Document document : documents) { + operations.add(new CustomOperation(document)); + } + + return Aggregation.newAggregation(operations); + } + + private static class CustomOperation implements AggregationOperation { + private Document document; + + public CustomOperation(Document operation) { + this.document = operation; + } + + public CustomOperation(String jOperation) { + this.document = Document.parse(jOperation); + } + + public Document toDocument(AggregationOperationContext context) { + return context.getMappedObject(this.document); + } + } +} diff --git a/src/main/java/com/midm/service/BaseService.java b/src/main/java/com/midm/service/BaseService.java new file mode 100644 index 0000000..f4de98a --- /dev/null +++ b/src/main/java/com/midm/service/BaseService.java @@ -0,0 +1,265 @@ +package com.midm.service; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.GroupByResult; +import com.midm.service.device.DeviceReportService; +import com.mitac.cell.db.util.McMongoUtils; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ScheduledFuture; +import org.bson.Document; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.aggregation.GroupOperation; +import org.springframework.data.mongodb.core.aggregation.MatchOperation; +import org.springframework.data.mongodb.core.index.Index; +import org.springframework.data.mongodb.core.index.IndexOperations; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +public class BaseService { + @Autowired + protected MongoTemplate mongoTemplate; + @Autowired + protected ThreadPoolTaskExecutor taskExecutor; + @Autowired + protected TaskScheduler taskScheduler; + protected Logger logger = LoggerFactory.getLogger(DeviceReportService.class); + + public MongoCollection getCollection(String collectionName) { + return this.mongoTemplate.getCollection(collectionName); + } + + public MongoCollection getCollection(Class entityClass) { + String collectionName = this.mongoTemplate.getCollectionName(entityClass); + return this.mongoTemplate.getCollection(collectionName); + } + + public boolean collectionExists(Class entityClass) { + return this.mongoTemplate.collectionExists(entityClass); + } + + public Object saveDocument(Object document) { + return this.mongoTemplate.save(document); + } + + public Object findById(Class entityClass, Object id) { + return id == null ? null : this.mongoTemplate.findOne(this.queryById(id), entityClass); + } + + public List findByIds(Class entityClass, Collection ids) { + if (ids != null) { + Query query = Query.query(Criteria.where("_id").in(ids)); + return this.mongoTemplate.find(query, entityClass); + } else { + return null; + } + } + + public boolean deleteById(Class entityClass, Object id) { + DeleteResult result = this.mongoTemplate.remove(this.queryById(id), entityClass); + return result.getDeletedCount() > 0L; + } + + public boolean existsById(Class entityClass, Object id) { + return this.mongoTemplate.exists(this.queryById(id), entityClass); + } + + public List findAll(Class entityClass) { + return this.mongoTemplate.findAll(entityClass); + } + + public long count(Class entityClass) { + return this.mongoTemplate.count(new Query(), entityClass); + } + + public List find(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction) { + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + return this.mongoTemplate.find(query, entityClass); + } + + public PageImpl findByPage(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction, Integer page, Integer size) { + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, entityClass); + if (total > 0L) { + page = this.page(total, page, size); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), entityClass); + return new PageImpl(result, pageable, total); + } else { + Pageable pageable = PageRequest.of(0, size); + return new PageImpl(new ArrayList(), pageable, total); + } + } + + public AggregationResults groupBy(String forWhat, String field, Criteria criteria) { + try { + MatchOperation matchStage = Aggregation.match(criteria); + GroupOperation groupByField = Aggregation.group(new String[]{field}).count().as("count").addToSet(field).as("groups"); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{matchStage, groupByField}); + AggregationResults result = this.mongoTemplate.aggregate(aggregation, forWhat, GroupByResult.class); + return result; + } catch (Exception var8) { + return null; + } + } + + public void update(Class entityClass, JsonObject jFilter, String key, Object value) { + Map map = new HashMap(); + map.put(key, value); + this.update(entityClass, jFilter, map); + } + + public void update(Class entityClass, JsonObject jFilter, Map valueMap) { + Query query = new Query(); + if (jFilter != null) { + McMongoUtils.addFilter(query, jFilter); + } + + Update update = new Update(); + valueMap.forEach((key, value) -> { + if (value == null) { + update.set(key, value); + } else { + update.unset(key); + } + + }); + this.mongoTemplate.updateMulti(query, update, entityClass); + } + + public void pull(Class entityClass, JsonObject jFilter, String key, Object arrayItem) { + Query query = new Query(); + if (jFilter != null) { + McMongoUtils.addFilter(query, jFilter); + } + + Update update = new Update(); + update.pull(key, arrayItem); + this.mongoTemplate.updateMulti(query, update, entityClass); + } + + public void addIndex(String collectionName, final String... indexes) { + if (indexes != null && indexes.length != 0) { + for(String index : indexes) { + this.addIndex(collectionName, index, Direction.ASC); + } + + } + } + + public void addIndex(String collectionName, final JsonObject jIndexes) { + if (jIndexes != null) { + for(Map.Entry jIndex : jIndexes.entrySet()) { + this.addIndex(collectionName, (String)jIndex.getKey(), Direction.fromString(((JsonElement)jIndex.getValue()).getAsString())); + } + + } + } + + public void addIndex(String collectionName, final String index, String direction) { + this.addIndex(collectionName, index, Direction.fromString(direction)); + } + + public void addIndex(String collectionName, final String index, Sort.Direction direction) { + IndexOperations operations = this.mongoTemplate.indexOps(collectionName); + operations.ensureIndex((new Index()).on(index, direction)); + } + + public void removeIndex(String collectionName, final String index) { + IndexOperations operations = this.mongoTemplate.indexOps(collectionName); + operations.dropIndex(index); + } + + public void unset(String collectionName, final String key) { + Update update = new Update(); + update.unset(key); + this.mongoTemplate.updateMulti(new Query(), update, collectionName); + } + + public UpdateResult unset(Class entityClass, Object id, String key) { + return this.mongoTemplate.updateFirst(this.queryById(id), (new Update()).unset(key), entityClass); + } + + public UpdateResult unset(Class entityClass, String key) { + return this.mongoTemplate.updateMulti(new Query(), (new Update()).unset(key), entityClass); + } + + public AggregationResults aggregate(String collection, List pipeline) { + return this.mongoTemplate.aggregate(Aggregations.from(pipeline), collection, Document.class); + } + + public Query queryById(Object id) { + return Query.query(Criteria.where("_id").is(id)); + } + + public Object convertToObject(Class entityClass, Document source) { + return this.mongoTemplate.getConverter().read(entityClass, source); + } + + public List convertToList(Class entityClass, List sources) { + if (sources != null && !sources.isEmpty()) { + List list = new ArrayList(); + sources.forEach((source) -> list.add(this.convertToObject(entityClass, source))); + return list; + } else { + return null; + } + } + + public int page(Long total, int page, int size) { + if (page == 0) { + return page; + } else { + long totalPages = total / (long)size; + if (total % (long)size > 0L) { + ++totalPages; + } + + return (long)(page + 1) <= totalPages ? page : 0; + } + } + + protected JsonObject getProfileFilter(String profileKey, String value) { + JsonObject jFilter = new JsonObject(); + jFilter.addProperty("profile." + profileKey, value); + return jFilter; + } + + protected Document toDocument(Object obj) { + Document doc = new Document(); + this.mongoTemplate.getConverter().write(obj, doc); + return doc; + } + + public void execute(Runnable task) { + this.taskExecutor.execute(task); + } + + public ScheduledFuture schedule(Runnable task, Date dateTime) { + return this.taskScheduler.schedule(task, dateTime); + } +} diff --git a/src/main/java/com/midm/service/EmailService.java b/src/main/java/com/midm/service/EmailService.java new file mode 100644 index 0000000..e2c9df4 --- /dev/null +++ b/src/main/java/com/midm/service/EmailService.java @@ -0,0 +1,347 @@ +package com.midm.service; + +import com.google.api.client.util.Strings; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.SiteRequest; +import com.midm.model.org.User; +import com.midm.service.file.FileService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.internet.mail.McMailSender; +import com.mitac.cell.utils.McStringUtils; +import com.mitac.cell.utils.McUrlUtils; +import com.mitac.cell.utils.McUuidUtils; +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Properties; +import java.util.UUID; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; +import org.thymeleaf.context.IContext; +import org.thymeleaf.context.WebContext; +import ua_parser.Client; + +@Service +public class EmailService { + @Autowired + ServletContext serveletContext; + @Autowired + private SettingsService settingsService; + @Autowired + @Qualifier("stringTemplateEngine") + private TemplateEngine stringTemplateEngine; + @Autowired + private FileService fileService; + private static JavaMailSenderImpl mailSender; + + public void sendTestMail(String email) { + String subject = "MiDM service test mail"; + Context context = new Context(); + String htmlContent = this.toHtmlContent(context, "testMail"); + this.sendMail(email, (String)null, "MiDM service test mail", htmlContent); + } + + public void sendInstallerFailedMail(List users, String category, UUID fileUuid, String fileName, String reason, String ssn) { + String subject = "[MiDM] Device failed to install."; + Context context = new Context(); + context.setVariable("category", category); + context.setVariable("fileUuid", fileUuid); + context.setVariable("fileName", fileName); + context.setVariable("reason", reason); + context.setVariable("ssn", ssn); + String htmlContent = this.toHtmlContent(context, "noti.install.failed"); + this.sendMail(users, "[MiDM] Device failed to install.", htmlContent); + } + + public void sendBatteryConditionAbnormalMail(List users, String siteName, String batterySerial, String deviceSerial, String model, String deviceGroupName) { + String subject = "[MiDM] Battery requires service notification"; + Context context = new Context(); + context.setVariable("siteName", siteName); + context.setVariable("batterySerial", batterySerial); + context.setVariable("deviceSerial", deviceSerial); + context.setVariable("model", model); + context.setVariable("deviceGroupName", deviceGroupName); + String htmlContent = this.toHtmlContent(context, "noti.batteryCondition.abnormal"); + this.sendMail(users, "[MiDM] Battery requires service notification", htmlContent); + } + + public void sendNotificationRequest(User user, NewsMessage newsMessage, String filePath, String fileName) { + String subject = String.format("[MiDM] Report for %s is ready", newsMessage.getForWhat()); + Context context = new Context(); + String userName = user.getName(); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + context.setVariable("fileName", fileName); + String htmlContent = this.toHtmlContent(context, "report.default"); + this.sendMail(user.getEmail(), user.getName(), subject, htmlContent, filePath, fileName); + } + + public void sendSiteLicenseRequestNoti(String email, NewsMessage newsMessage) { + String subject = String.format("[MiDM] Site License is requested"); + Context context = new Context(); + String userName = email.substring(0, email.indexOf("@")); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + String htmlContent = this.toHtmlContent(context, "site.license.request"); + this.sendMail(email, userName, subject, htmlContent); + } + + public void sendSiteUpgradeRequestNoti(String email, NewsMessage newsMessage) { + String subject = String.format("[MiDM] Site Upgrade is requested"); + Context context = new Context(); + String userName = email.substring(0, email.indexOf("@")); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + String htmlContent = this.toHtmlContent(context, "site.upgrade.request"); + this.sendMail(email, userName, subject, htmlContent); + } + + public void sendSiteLicenseNoti(User user, NewsMessage newsMessage) { + String subject = String.format("[MiDM] Site License is ready"); + Context context = new Context(); + String userName = user.getName(); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + String htmlContent = this.toHtmlContent(context, "site.license"); + this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); + } + + public void sendSiteUpgradeNoti(User user, NewsMessage newsMessage) { + String subject = String.format("[MiDM] Site Upgrade Success"); + Context context = new Context(); + String userName = user.getName(); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + String htmlContent = this.toHtmlContent(context, "site.upgrade"); + this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); + } + + public void sendHostLicenseRequestNoti(String email, NewsMessage newsMessage) { + String subject = String.format("[MiDM] Host License is requested"); + Context context = new Context(); + String userName = email.substring(0, email.indexOf("@")); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + String htmlContent = this.toHtmlContent(context, "host.license.request"); + this.sendMail(email, userName, subject, htmlContent); + } + + public void sendHostLicenseNoti(User user, NewsMessage newsMessage) { + String subject = String.format("[MiDM] Host License is ready"); + Context context = new Context(); + String userName = user.getName(); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + String htmlContent = this.toHtmlContent(context, "host.license"); + this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); + } + + public void sendDevicePullNotificationRequest(User user, NewsMessage newsMessage, String filePath, String fileName) { + String deviceSerial = (String)newsMessage.getReference().get("deviceSerial"); + String subject = String.format("[MiDM] File from device is ready", deviceSerial); + Context context = new Context(); + String userName = user.getName(); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("news", newsMessage); + context.setVariable("fileName", fileName); + context.setVariable("deviceSerial", deviceSerial); + String htmlContent = this.toHtmlContent(context, "noti.request.pullFile"); + this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); + } + + public void sendStandaloneMessage(String subject, User user, String content) { + Context context = new Context(); + String userName = user.getName(); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + context.setVariable("content", content); + String htmlContent = this.toHtmlContent(context, "standaloneMessage"); + this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); + } + + public void sendActivatedNotification(HttpServletRequest request, HttpServletResponse response, User user) { + String subject = "Your MiDM account has been activated"; + WebContext context = this.getContext(request, response); + String userName = user.getName(); + context.setVariable("user", user); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + String homeUrl = McUrlUtils.getHostUrl(request); + context.setVariable("homeUrl", homeUrl); + String htmlContent = this.toHtmlContent(context, "accountActivated"); + this.sendMail(user.getEmail(), user.getName(), "Your MiDM account has been activated", htmlContent); + } + + public void sendPasswordResetRequest(HttpServletRequest request, HttpServletResponse response, User user, UUID passwordResetToken) { + String subject = "Reset your MiDM password"; + WebContext context = this.getContext(request, response); + String userName = user.getName(); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + String var10000 = McUrlUtils.getHostUrl(request); + String activationUrl = var10000 + "/resetPassword?token=" + McUuidUtils.toBase64String(passwordResetToken); + context.setVariable("passwordResetUrl", activationUrl); + String htmlContent = this.toHtmlContent(context, "passwordReset"); + this.sendMail(user.getEmail(), user.getName(), "Reset your MiDM password", htmlContent); + } + + public void sendExceedLoginFailure(HttpServletRequest request, HttpServletResponse response, User user, DateTime retryAfter, Client client, String remoteIp) { + String subject = "Exceed maximum number of login failure"; + WebContext context = this.getContext(request, response); + String userName = user.getName(); + context.setVariable("user", user); + context.setVariable("retryAfter", retryAfter.toString("yyyy-MM-dd hh:mm:ss")); + context.setVariable("client", client); + context.setVariable("remoteIp", remoteIp); + context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); + String homeUrl = McUrlUtils.getHostUrl(request); + context.setVariable("homeUrl", homeUrl); + String htmlContent = this.toHtmlContent(context, "account.login.failure"); + this.sendMail(user.getEmail(), user.getName(), "Exceed maximum number of login failure", htmlContent); + } + + public void sendSiteTrial(HttpServletRequest request, HttpServletResponse response, SiteRequest siteRequest) { + InternetAddress[] recipients = this.settingsService.siteRequestRecipients(); + if (recipients != null && recipients.length > 0) { + String subject = "[MiDM] Free trial request from " + siteRequest.getCompany(); + WebContext context = this.getContext(request, response); + context.setVariable("siteRequest", siteRequest); + String htmlContent = this.toHtmlContent(context, "siteRequest"); + + for(InternetAddress address : recipients) { + this.sendMail(address.getAddress(), address.getPersonal(), subject, htmlContent); + } + } + + } + + @Async + public void sendMail(String toMail, String toName, String subject, String htmlContent) { + McMailSender mailSender = this.getMailSender(); + if (mailSender != null) { + mailSender.addTo(toMail, toName); + mailSender.setSubject(subject); + mailSender.setHtml(htmlContent); + mailSender.send(); + } + } + + @Async + public void sendMail(Collection users, String subject, String htmlContent) { + McMailSender mailSender = this.getMailSender(); + if (mailSender != null) { + List addrs = new ArrayList(); + + for(User u : users) { + InternetAddress addr = null; + + try { + addr = new InternetAddress(u.getEmail(), u.getName()); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + + try { + addr = new InternetAddress(u.getEmail()); + } catch (AddressException e1) { + e1.printStackTrace(); + continue; + } + } + + addrs.add(addr); + } + + mailSender.setTo(addrs); + mailSender.setSubject(subject); + mailSender.setHtml(htmlContent); + mailSender.send(); + } + } + + @Async + public void sendMail(String toMail, String toName, String subject, String htmlContent, String filePath, String fileName) { + McMailSender mailSender = this.getMailSender(); + if (mailSender != null) { + mailSender.addTo(toMail, toName); + mailSender.setSubject(subject); + mailSender.setHtml(htmlContent); + if (!Strings.isNullOrEmpty(filePath)) { + File file = new File(filePath); + if (file.exists()) { + if (Strings.isNullOrEmpty(fileName)) { + fileName = file.getName(); + } + + mailSender.addAttachment(file, fileName); + } + } + + mailSender.send(); + } + } + + private WebContext getContext(HttpServletRequest request, HttpServletResponse response) { + return new WebContext(request, response, this.serveletContext, request.getLocale()); + } + + public McMailSender getMailSender(String subject, String content, boolean isHtml) { + McMailSender sender = this.getMailSender(); + if (sender != null) { + sender.setSubject(subject); + sender.setContent(content, isHtml); + } + + return sender; + } + + public boolean hasMailServer() { + return !Strings.isNullOrEmpty(this.settingsService.get("mail.host")); + } + + public McMailSender getMailSender() { + if (mailSender == null) { + this.updateMailSender(); + } + + return mailSender == null ? null : new McMailSender(mailSender, this.settingsService.get("mail.from.mail"), this.settingsService.get("mail.from.name")); + } + + public void updateMailSender() { + String host = this.settingsService.get("mail.host"); + if (Strings.isNullOrEmpty(host)) { + mailSender = null; + } else { + mailSender = new JavaMailSenderImpl(); + mailSender.setHost(host); + int port = this.settingsService.getInt("mail.port"); + mailSender.setPort(port < 0 ? 25 : port); + String protocol = this.settingsService.get("mail.protocol"); + mailSender.setProtocol(Strings.isNullOrEmpty(protocol) ? "smtp" : protocol); + String userName = this.settingsService.get("mail.username"); + if (!Strings.isNullOrEmpty(userName)) { + mailSender.setUsername(userName); + String password = this.settingsService.get("mail.password"); + mailSender.setPassword(password); + } + + mailSender.setDefaultEncoding("UTF-8"); + Properties mailProperties = mailSender.getJavaMailProperties(); + mailProperties.put("mail.smtp.starttls.enable", "true"); + } + } + + public String toHtmlContent(IContext context, String templateName) { + String htmlTemplate = this.fileService.getResourceToString(String.format("mail/%s.html", templateName), false); + return this.stringTemplateEngine.process(htmlTemplate, context); + } +} diff --git a/src/main/java/com/midm/service/EmailTemplateResolver.java b/src/main/java/com/midm/service/EmailTemplateResolver.java new file mode 100644 index 0000000..9422296 --- /dev/null +++ b/src/main/java/com/midm/service/EmailTemplateResolver.java @@ -0,0 +1,4 @@ +package com.midm.service; + +public class EmailTemplateResolver { +} diff --git a/src/main/java/com/midm/service/ExternalApiService.java b/src/main/java/com/midm/service/ExternalApiService.java new file mode 100644 index 0000000..2555771 --- /dev/null +++ b/src/main/java/com/midm/service/ExternalApiService.java @@ -0,0 +1,158 @@ +package com.midm.service; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.device.DeviceReport; +import com.midm.model.org.Site; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.util.Collection; +import java.util.concurrent.TimeUnit; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.bson.Document; +import org.springframework.data.util.Pair; + +public class ExternalApiService { + private static OkHttpClient client; + + public static void doRequestCallback(Site site, Collection reports) { + try { + if (site == null) { + return; + } + + DbObject callback = site.getCallbackSetting(); + String url = callback.getString("url"); + if (Strings.isNullOrEmpty(url)) { + return; + } + + RequestBody requestBody = RequestBody.create(McJsonUtils.toJson(reports), MediaType.parse("application/json")); + Request.Builder builder = (new Request.Builder()).url(url).post(requestBody); + String key = callback.getString("key"); + if (!Strings.isNullOrEmpty(key)) { + builder.addHeader("apikey", key); + } + + Request request = builder.build(); + client.newCall(request).enqueue(new Callback() { + public void onFailure(Call call, IOException e) { + } + + public void onResponse(Call call, Response response) throws IOException { + response.close(); + } + }); + } catch (Exception var8) { + } + + } + + public static Pair doRequestRsaIsValid(String url, String serialNo, String encryptString) { + if (Strings.isNullOrEmpty(url)) { + return Pair.of(true, ""); + } else { + JsonObject input = new JsonObject(); + input.addProperty("sn", serialNo); + input.addProperty("secret", encryptString); + RequestBody requestBody = RequestBody.create(McJsonUtils.toJson(input), MediaType.parse("application/json")); + Request.Builder builder = (new Request.Builder()).url(url).post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + + Pair var15; + label73: { + Pair var11; + label74: { + Pair decryptStrings; + try { + if (response.code() != 200) { + var15 = Pair.of(false, String.format("InvalidRsa, response code: %s, url: %s ", response.code(), url)); + break label73; + } + + Document json = (Document)McJsonUtils.toObject(response.body().string(), Document.class); + REPONSE_VMAX_CODE responseCode = ExternalApiService.REPONSE_VMAX_CODE.get(json.getString("code")); + if (responseCode == ExternalApiService.REPONSE_VMAX_CODE.SUCCESS) { + String[] decryptStrings = json.getString("data").split(","); + var11 = decryptStrings[0].equals(serialNo) ? Pair.of(true, "") : Pair.of(false, "InvalidRsa, Device bear wrong key"); + break label74; + } + + decryptStrings = Pair.of(false, String.format("InvalidRsa, responseVmaxcode: %s, url: %s", responseCode.toString(), url)); + } catch (Throwable var13) { + if (response != null) { + try { + response.close(); + } catch (Throwable var12) { + var13.addSuppressed(var12); + } + } + + throw var13; + } + + if (response != null) { + response.close(); + } + + return decryptStrings; + } + + if (response != null) { + response.close(); + } + + return var11; + } + + if (response != null) { + response.close(); + } + + return var15; + } catch (Exception e) { + return Pair.of(false, String.format("InvalidRsa, exception: %s, url: %s", e.getMessage(), url)); + } + } + } + + static { + client = (new OkHttpClient.Builder()).connectTimeout(5L, TimeUnit.SECONDS).writeTimeout(30L, TimeUnit.SECONDS).build(); + } + + private static enum REPONSE_VMAX_CODE { + SUCCESS("S00000"), + ERROR_DEVICE_RSA_KEY_ID_NOT_FOUND("E10028"), + ERROR_DECRYPT_FAILED("E10029"), + BAD_PARAMETERS("E80006"), + ERR_DEVICE_NOT_FOUND("E80020"), + UNKNOWN_EXCEPTION("E99999"), + UNKNOWN_ERROR_IN_MIDM("E0000"); + + private String code; + + private REPONSE_VMAX_CODE(String code) { + this.code = code; + } + + private static REPONSE_VMAX_CODE get(String requestText) { + for(REPONSE_VMAX_CODE c : values()) { + if (c.code.equalsIgnoreCase(requestText.trim())) { + return c; + } + } + + return UNKNOWN_ERROR_IN_MIDM; + } + } +} diff --git a/src/main/java/com/midm/service/GeneralService.java b/src/main/java/com/midm/service/GeneralService.java new file mode 100644 index 0000000..2b60767 --- /dev/null +++ b/src/main/java/com/midm/service/GeneralService.java @@ -0,0 +1,49 @@ +package com.midm.service; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.mitac.cell.utils.McStringUtils; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.MongoOperations; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class GeneralService { + @Autowired + protected MongoTemplate mongoTemplate; + protected MongoOperations mongoOperations; + + public GeneralService() { + this.mongoOperations = this.mongoTemplate; + } + + protected Query toQuery(JsonObject jFilter, Integer page, Integer size, String sortBy, String directionValue) { + Query query = new Query(); + if (McStringUtils.isValid(sortBy)) { + Sort.Direction direction = !McStringUtils.isNullOrEmpty(directionValue) && !directionValue.toUpperCase().startsWith("D") ? Direction.ASC : Direction.DESC; + query.with(Sort.by(direction, new String[]{sortBy})); + } + + if (page != null && size != null) { + query.with(PageRequest.of(page, size)); + } + + if (jFilter != null) { + for(Map.Entry jEntry : jFilter.entrySet()) { + if (jEntry.getValue() != null) { + String value = ((JsonElement)jEntry.getValue()).getAsString(); + query.addCriteria(Criteria.where((String)jEntry.getKey()).regex(value)); + } + } + } + + return query; + } +} diff --git a/src/main/java/com/midm/service/ScheduledTaskService.java b/src/main/java/com/midm/service/ScheduledTaskService.java new file mode 100644 index 0000000..dc2d275 --- /dev/null +++ b/src/main/java/com/midm/service/ScheduledTaskService.java @@ -0,0 +1,96 @@ +package com.midm.service; + +import com.midm.model.device.Device; +import com.midm.model.device.DeviceProfile; +import com.midm.service.device.ProfileService; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ScheduledTaskService { + @Autowired + private ProfileService profileService; + private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); + private static Map scheduleMap = new ConcurrentHashMap(); + + public void scheduleToUpdateProfile(Device device) { + this.scheduleToUpdateProfile((Device)device, 5); + } + + public void scheduleToUpdateProfile(Device device, int minLater) { + if (device != null) { + ScheduledFuture task = (ScheduledFuture)scheduleMap.get(device.getUuid()); + if (task != null) { + task.cancel(true); + } + + scheduleMap.put(device.getUuid(), scheduledExecutorService.schedule(new DeviceUpdateRunnable(device), (long)minLater, TimeUnit.MINUTES)); + } + } + + public void scheduleToUpdateProfile(UUID deviceUuid, int minLater) { + if (deviceUuid != null) { + ScheduledFuture task = (ScheduledFuture)scheduleMap.get(deviceUuid); + if (task != null) { + task.cancel(true); + } + + scheduleMap.put(deviceUuid, scheduledExecutorService.schedule(new DeviceUpdateRunnable(deviceUuid), (long)minLater, TimeUnit.MINUTES)); + } + } + + public void cancelSchedule(UUID uuid) { + if (scheduleMap.containsKey(uuid)) { + ((ScheduledFuture)scheduleMap.get(uuid)).cancel(true); + } + + } + + public void scheduleToUpdateProfile(DeviceProfile deviceProfile) { + if (deviceProfile != null && deviceProfile.getEnabled()) { + ScheduledFuture task = (ScheduledFuture)scheduleMap.get(deviceProfile.getUuid()); + if (task != null) { + task.cancel(true); + } + + scheduleMap.put(deviceProfile.getUuid(), scheduledExecutorService.schedule(new ProfileUpdateRunnable(deviceProfile), 5L, TimeUnit.MINUTES)); + } + } + + class DeviceUpdateRunnable implements Runnable { + private UUID deviceUuid; + + public DeviceUpdateRunnable(Device device) { + this.deviceUuid = device.getUuid(); + } + + public DeviceUpdateRunnable(UUID deviceUuid) { + this.deviceUuid = deviceUuid; + } + + public void run() { + ScheduledTaskService.this.profileService.notifyUpdate(this.deviceUuid); + ScheduledTaskService.scheduleMap.remove(this.deviceUuid); + } + } + + class ProfileUpdateRunnable implements Runnable { + private DeviceProfile profile; + + public ProfileUpdateRunnable(DeviceProfile profile) { + this.profile = profile; + } + + public void run() { + ScheduledTaskService.scheduleMap.remove(this.profile.getUuid()); + ScheduledTaskService.this.profileService.notifyUpdate(this.profile, false); + } + } +} diff --git a/src/main/java/com/midm/service/battery/BatteryService.java b/src/main/java/com/midm/service/battery/BatteryService.java new file mode 100644 index 0000000..1d70f17 --- /dev/null +++ b/src/main/java/com/midm/service/battery/BatteryService.java @@ -0,0 +1,475 @@ +package com.midm.service.battery; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import com.midm.constant.LocaleConst; +import com.midm.model.battery.Battery; +import com.midm.model.battery.BatteryLog; +import com.midm.model.battery.ValueWithTime; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.log.MidmLog; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.device.DeviceService; +import com.midm.service.log.LogService; +import com.midm.service.org.SiteService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.UpdateResult; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +/** + * ====================================================================================== + * IoT 电池健康度遥测与电池管理系统 (BMS - Battery Management System Service) + * ====================================================================================== + * + *

【业务背景与 IoT 核心价值】 + * 1. 行业智能终端(如物流仓储 PDA、医院查房平板、巡检仪)多采用可更换式锂电池, + * 电池过热、循环寿命损耗或鼓包是导致设备离线甚至安全事故的主要原因。 + * 2. 核心功能: + * - 遥测数据存储:基于 MongoDB 采集电池序列号、充放电循环次数(Charge Cycles)、 + * 健康度指标(SOH - State Of Health)、温度与电压时序数据; + * - 高级聚合分析(Aggregation Pipeline):基于 `$lookup` 管道多表关联电池档案与日志, + * 支持毫秒级时间范围遥测曲线回溯; + * - 异常监控与自动化告警:当电池劣化状态达到 `SERVICE_SOON` 预警阈值时, + * 自动触发邮件通知发往企业管理员(SUPERVISOR)。 + * 3. 存储优化设计({@link #leaveLast}): + * - 对温度、电压等高频时序数据采用定期抽样与末位保留策略,有效防止文档尺寸膨胀。 + * + * @author MiDM Core Platform Team + */ +@Service +public class BatteryService extends BaseService { + + @Autowired + DeviceService deviceService; + + @Autowired + SiteService siteService; + + @Autowired + private LogService logService; + + @Autowired + private EmailService emailService; + + /** + * 保存或更新电池档案基础信息 + * + * @param battery 电池实体 + * @return 持久化后的电池对象 + */ + public Battery save(Battery battery) { + if (battery != null && !McStringUtils.isNullOrEmpty(battery.getBatterySerial())) { + if (battery.getDeviceSerial() == null) { + battery.setRegisterState("registered"); + } else { + Device device = this.deviceService.findBySerialNo(battery.getDeviceSerial()); + if (this.exists(battery.getBatterySerial())) { + battery = this.findByBatterySerial(battery.getBatterySerial()); + battery.setUpdated(); + } + + if (device != null) { + battery.setSiteUuid(device.getSiteUuid()); + battery.setDeviceSerial(device.getSerialNo()); + } + + battery.setRegisterState("enrolled"); + } + + return (Battery)this.saveDocument(battery); + } else { + return null; + } + } + + /** + * 批量保存电池档案 + */ + public Collection saveBatteries(Collection batteries) { + Collection saveList = new ArrayList(); + for(Battery battery : (Collection)batteries) { + Battery saveBattery = this.save(battery); + if (saveBattery != null) { + saveList.add(saveBattery); + } + } + return saveList; + } + + /** + * 检查指定序列号的电池是否已存在于数据库中 + */ + public boolean exists(String batterySerial) { + Criteria criteria = Criteria.where(String.format("%s.%s.%s", "profile", "hardware_info", "batterySerial")).is(batterySerial); + return this.mongoTemplate.exists(Query.query(criteria), Battery.class); + } + + /** + * 【复杂多条件分页查询】多租户下动态过滤检索电池列表 + * + * @param siteUuid 租户 ID + * @param filter 动态过滤条件(状态、归属人、异常条件等级等) + * @param page 页码 + * @param size 单页大小 + * @param sortBy 排序字段 + * @param direction 升序/降序 + * @return 分页结果封装 + */ + public Page findBatteries(UUID siteUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.hardware_info.batterySerial"; + direction = Direction.ASC; + } + + List criterias = new ArrayList(); + criterias.add(Criteria.where("siteUuid").is(siteUuid)); + if (filter != null) { + for(Map.Entry entry : filter.entrySet()) { + String key = (String)entry.getKey(); + JsonElement value = (JsonElement)entry.getValue(); + switch (key) { + case "siteUuid": + break; + case "owner.uuid": + criterias.add(Criteria.where("owner.$id").is(UUID.fromString(value.getAsString()))); + break; + case "states.batteryCondition": + int batteryCondition = value.getAsInt(); + if (batteryCondition >= 0 && batteryCondition <= 2) { + criterias.add(Criteria.where(key).is(batteryCondition)); + } else { + criterias.add(Criteria.where(key).nin(new Object[]{0, 1, 2})); + } + break; + default: + // 正则转义模糊检索 + criterias.add(Criteria.where(key).regex(McMongoUtils.escapedPattern(value.getAsString()))); + } + } + } + + Query query = Query.query((new Criteria()).andOperator(criterias)); + Sort sort = Sort.by(direction, new String[]{sortBy}); + if (!sortBy.equals("profile.hardware_info.batterySerial")) { + sort = sort.and(Sort.by(direction, new String[]{"profile.hardware_info.batterySerial"})); + } + + query.with(sort); + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, Battery.class); + if (total > 0L) { + page = this.page(total, page, size); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), Battery.class); + + // 关联补充设备分组层级路径(如 "华东大区/仓储一号库") + for(Battery battery : result) { + Device device = this.deviceService.findBySerialNo(battery.getDeviceSerial()); + if (device != null) { + DeviceGroup group = device.getDeviceGroup(); + if (group != null) { + battery.setDeviceGroupPath(this.deviceService.getGroupPath(group)); + } + } + } + + return new PageImpl(result, pageable, total); + } else { + Pageable pageable = PageRequest.of(0, size); + return new PageImpl(new ArrayList(), pageable, total); + } + } + + /** + * 依据电池序列号与上报时间查询单条遥测日志 + */ + public BatteryLog findBatteryLog(String batterySerial, Date reportedAt) { + Criteria criteria = Criteria.where("batterySerial").is(batterySerial).and("reportedAt").is(reportedAt); + return (BatteryLog)this.mongoTemplate.findOne(Query.query(criteria), BatteryLog.class); + } + + /** + * 【MongoDB 聚合管道优化】基于 $lookup 与 $replaceRoot 快速回溯设备电池的历史时序日志 + * + *

管道执行流程: + * 1. $match:根据设备序列号定位设备硬件档案; + * 2. $lookup:跨集合关联 batteryLog,在子管道中根据时间范围 [from, to) 过滤遥测记录; + * 3. $project & $unwind:展开关联数组; + * 4. $replaceRoot:将日志文档提升为根节点输出; + * 5. $sort:按时间升序返回完整的遥测曲线数据。 + * + * @param deviceSerial 设备唯一序列号 + * @param from 起始时间 + * @param to 结束时间 + * @return 时序日志列表 + */ + public List findBatteryLogByRange(String deviceSerial, Date from, Date to) { + AggregationOperation lookupOp = Aggregations.newOperation(new Document("$lookup", (new Document("from", "batteryLog")) + .append("localField", "profile.hardware_info.batterySerial") + .append("foreignField", "batterySerial") + .append("pipeline", Arrays.asList(new Document("$match", new Document("$and", Arrays.asList( + new Document("reportedAt", new Document("$gte", from)), + new Document("reportedAt", new Document("$lt", to)) + ))))).append("as", "bLog"))); + + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{ + Aggregation.match(Criteria.where("profile.hardware_info.deviceSerial").is(deviceSerial)), + lookupOp, + Aggregations.newOperation("{$project: {bLog: 1, _id:0}}"), + Aggregations.newOperation("{$unwind: '$bLog'}"), + Aggregations.newOperation("{$replaceRoot: {newRoot: '$bLog'}}"), + Aggregations.newOperation("{$sort: {reportedAt:1}}") + }).withOptions(Aggregation.newAggregationOptions().collation(LocaleConst.COLLATION_DEFAULT).build()); + + return this.mongoTemplate.aggregate(aggregation, Battery.class, BatteryLog.class).getMappedResults(); + } + + /** + * 保存单条电池日志 + */ + public BatteryLog save(BatteryLog log, String category) { + if (log == null) { + return null; + } else { + if (!McStringUtils.isNullOrEmpty(category)) { + log.setCategory(category); + } + return (BatteryLog)this.saveDocument(log); + } + } + + /** + * 【批量遥测日志入库与状态同步】 + * + *

1. 批量入库或更新时序日志(幂等校验); + * 2. 提取最新一条日志同步更新至 Battery 主实体的 states 字段; + * 3. 同步触发设备状态与告警检查。 + */ + public List saveBatteryLogs(List logs, String category) { + if (logs != null && !logs.isEmpty()) { + List saveList = new ArrayList(); + String batterySerial = ((BatteryLog)logs.get(0)).getBatterySerial(); + if (McStringUtils.isNullOrEmpty(batterySerial)) { + return saveList; + } else { + Battery battery = this.findByBatterySerial(batterySerial); + if (battery == null) { + return saveList; + } else { + for(BatteryLog log : (List)logs) { + BatteryLog exist = this.findBatteryLog(batterySerial, log.getReportedAt()); + if (exist != null) { + UpdateResult result = this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(exist.getUuid())), (new Update()).set("states", log.getStates()).set("updated", new Date()), BatteryLog.class); + if (result.getModifiedCount() != 0L) { + saveList.add(log); + } + } else { + BatteryLog saveLog = this.save(log, category); + if (saveLog != null) { + saveList.add(saveLog); + } + } + } + + if (!saveList.isEmpty()) { + Device device = this.deviceService.findBySerialNo(battery.getDeviceSerial()); + if (device != null) { + // 若电池被拆换到另一租户设备上,自动校准归属租户 + if (!device.getSiteUuid().equals(battery.getSiteUuid())) { + String logMessage = String.format("Change battery siteUuid from %s to device siteUuid %s", battery.getSiteUuid(), device.getSiteUuid()); + MidmLog midmLog = new MidmLog(); + midmLog.setForWhat(battery.getUuid()); + midmLog.setCategory("update"); + midmLog.setLog(logMessage); + this.logService.save(midmLog); + battery.setSiteUuid(device.getSiteUuid()); + } + + BatteryLog latestBatteryLog = null; + for(BatteryLog log : saveList) { + if (latestBatteryLog == null || log.getReportedAt().after(latestBatteryLog.getReportedAt())) { + latestBatteryLog = log; + } + } + + this.updateBatteryFromBatteryLog(device, battery, latestBatteryLog.getStates()); + this.deviceService.update(device.getUuid(), "states.batteryCondition", latestBatteryLog.getStates().get("batteryCondition")); + } + } + + return saveList; + } + } + } else { + return new ArrayList(); + } + } + + /** + * 批量修改电池登记状态(enrolled, registered, decommissioned) + */ + public void setRegisterState(List batteryUuids, String state) { + if (batteryUuids != null && !batteryUuids.isEmpty()) { + Query query = Query.query(Criteria.where("_id").in(batteryUuids)); + Update update = Update.update("states.state", state); + this.mongoTemplate.updateMulti(query, update, Battery.class); + + for(UUID uuid : (List)batteryUuids) { + MidmLog midmLog = new MidmLog(); + midmLog.setForWhat(uuid); + midmLog.setCategory("update"); + midmLog.setLog("Change registerState to " + state); + this.logService.save(midmLog); + } + } + } + + /** + * 根据电池序列号查找档案 + */ + public Battery findByBatterySerial(String batterySerial) { + if (McStringUtils.isNullOrEmpty(batterySerial)) { + return null; + } else { + Criteria criteria = Criteria.where(String.format("%s.%s.%s", "profile", "hardware_info", "batterySerial")).is(batterySerial); + return (Battery)this.mongoTemplate.findOne(Query.query(criteria), Battery.class); + } + } + + /** + * 查询指定设备绑定的最新电池记录 + */ + public Battery findLatestByDeviceSerial(String deviceSerial) { + if (McStringUtils.isNullOrEmpty(deviceSerial)) { + return null; + } else { + Criteria criteria = Criteria.where(String.format("%s.%s.%s", "profile", "hardware_info", "deviceSerial")).is(deviceSerial); + Sort sort = Sort.by(Direction.DESC, new String[]{"updated"}); + Query query = Query.query(criteria).with(sort).limit(1); + return (Battery)this.mongoTemplate.findOne(query, Battery.class); + } + } + + /** + * 处理即时心跳上报的电池简略状态(包含老化告警触发) + */ + public void updateBatteryFromInstant(Device device, DbObject batteryObj) { + if (batteryObj != null) { + String batterySerial = batteryObj.getString("batterySerial"); + if (batterySerial == null) { + return; + } + + Battery battery = this.findByBatterySerial(batterySerial); + if (battery == null) { + return; + } + + // 更新健康度 SOH 与充放电循环次数 + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(battery.getUuid())), + (new Update()).set("states.batteryCondition", batteryObj.get("batteryCondition")) + .set("states.soh", batteryObj.get("soh")) + .set("states.chargeCycle", batteryObj.get("chargeCycle")) + .set("updated", new Date()), + Battery.class); + + int batteryConditionOrigin = battery.getBatteryCondition(); + int batteryConditionNew = batteryObj.getInteger("batteryCondition", -1); + // 检查是否需要触发运维告警邮件 + this.sendMailIfNeed(battery, batteryConditionOrigin, batteryConditionNew, device); + if (batteryObj.containsKey("batteryCondition")) { + this.deviceService.update(device.getUuid(), "states.batteryCondition", batteryObj.get("batteryCondition")); + } + } + } + + /** + * 从最新遥测日志同步刷新电池快照,并对高频时序数据执行保留压缩 + */ + public void updateBatteryFromBatteryLog(Device device, Battery battery, DbObject latestBatteryLogState) { + if (latestBatteryLogState != null) { + int batteryConditionOrigin = battery.getBatteryCondition(); + DbObject states = (DbObject)McJsonUtils.clone(latestBatteryLogState); + states.put("state", battery.getStates().getString("state")); + // 仅保留温度、电压、电量、充电状态的最近一个采样点,防止快照过度膨胀 + this.leaveLast(states, Arrays.asList("temperature", "voltage", "level", "charginStatus", "plugged")); + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(battery.getUuid())), (new Update()).set("states", states).set("updated", new Date()), Battery.class); + this.sendMailIfNeed(battery, batteryConditionOrigin, latestBatteryLogState.getInteger("batteryCondition", -1), device); + } + } + + /** + * 【自动化故障预警机制】当电池状态劣化进入 SERVICE_SOON(即将损坏/急需更换)时发送告警邮件 + */ + private void sendMailIfNeed(Battery battery, int batteryConditionOrigin, int batteryConditionNew, Device device) { + Site site = this.siteService.findByUuid(battery.getSiteUuid()); + if (site != null && site.isStandardWithBatteryPro() && site.notifyBatteryConditionMail() && + batteryConditionOrigin != Battery.BATTERY_CONDITION.SERVICE_SOON.getValue() && + batteryConditionNew == Battery.BATTERY_CONDITION.SERVICE_SOON.getValue()) { + + // 获取该租户下的所有运维主管(SUPERVISOR) + Set roles = new HashSet(Arrays.asList("SUPERVISOR")); + List profileManagers = this.siteService.findUserByRole(site, roles); + DeviceGroup group = device.getDeviceGroup(); + String deviceGroupPath = null; + if (group != null) { + deviceGroupPath = this.deviceService.getGroupPath(group); + } + + // 发送图文并茂的异常告警邮件 + this.emailService.sendBatteryConditionAbnormalMail(profileManagers, site.getName(), battery.getBatterySerial(), battery.getDeviceSerial(), battery.getModel(), deviceGroupPath); + } + } + + /** + * 【时序存储数据降采样压缩】对数组型时序指标只截取并保留最新一条采样值 + */ + private void leaveLast(DbObject states, List keys) { + for(String key : (List)keys) { + List tList = (List)McJsonUtils.toObject(McJsonUtils.toJson(states.get(key)), (new TypeToken() { + }).getType()); + if (tList != null && !tList.isEmpty()) { + ValueWithTime latestOne = null; + for(ValueWithTime t : tList) { + if (latestOne == null || t.getReportedAt().after(latestOne.getReportedAt())) { + latestOne = t; + } + } + DbObject obj = new DbObject(); + obj.append("reportedAt", latestOne.getReportedAt()).append("value", latestOne.getValue()); + states.put(key, Arrays.asList(obj)); + } + } + } +} diff --git a/src/main/java/com/midm/service/cloudStorage/AwsS3.java b/src/main/java/com/midm/service/cloudStorage/AwsS3.java new file mode 100644 index 0000000..001b856 --- /dev/null +++ b/src/main/java/com/midm/service/cloudStorage/AwsS3.java @@ -0,0 +1,193 @@ +package com.midm.service.cloudStorage; + +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3ClientBuilder; +import com.amazonaws.services.s3.model.CannedAccessControlList; +import com.amazonaws.services.s3.model.CopyObjectRequest; +import com.amazonaws.services.s3.model.ObjectListing; +import com.amazonaws.services.s3.model.ObjectMetadata; +import com.amazonaws.services.s3.model.PutObjectRequest; +import com.amazonaws.services.s3.model.S3ObjectSummary; +import com.google.common.base.Strings; +import com.midm.service.system.SettingsService; +import com.mitac.cell.internet.http.McHttpClient; +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AwsS3 extends CloudStorage { + private static final String PROPERTY_ACCESS_KEY = "aws.s3.accessKey"; + private static final String PROPERTY_SECRET = "aws.s3.secret"; + private static final String PROPERTY_REGION = "aws.s3.region"; + private static final String PROPERTY_BUCKET = "aws.s3.bucket"; + private static final String PROPERTY_PREFIX = "aws.s3.prefix"; + private String accessKey = ""; + private String secretKey = ""; + private String region = ""; + private AmazonS3 s3Client; + + public AwsS3(SettingsService settingsService) { + super(settingsService); + this.refreshClient(); + } + + public String getUrl(Object... paths) { + if (this.exists(paths)) { + Date expiry = this.getUrlExpiry(); + URL url = this.s3Client.generatePresignedUrl(this.getBucketName(), this.generateObjectKey(paths), expiry); + return url == null ? null : url.toString(); + } else { + return null; + } + } + + public boolean upload(File file, String orgFileName, String contentType, Object... paths) { + if (this.s3Client != null) { + PutObjectRequest request = (new PutObjectRequest(this.getBucketName(), this.generateObjectKey(paths), file)).withCannedAcl(CannedAccessControlList.Private); + ObjectMetadata metaData = new ObjectMetadata(); + metaData.setContentType(contentType); + metaData.setContentDisposition(McHttpClient.toContentDisposition(orgFileName)); + request.setMetadata(metaData); + this.s3Client.putObject(request); + return this.exists(paths); + } else { + return false; + } + } + + public void updateMetaInfo(String orgFileName, String contentType, Object... paths) { + String bucketName = this.getBucketName(); + String objectName = this.generateObjectKey(paths); + if (this.s3Client.doesObjectExist(bucketName, objectName)) { + ObjectMetadata metaData = this.s3Client.getObjectMetadata(bucketName, objectName); + String prevContentType = metaData.getContentType(); + String prevContentDisposition = metaData.getContentDisposition(); + String contentDisposition = McHttpClient.toContentDisposition(orgFileName); + if (Strings.isNullOrEmpty(prevContentType) || !prevContentType.equals(contentType) || Strings.isNullOrEmpty(prevContentDisposition) || !prevContentDisposition.equals(contentDisposition)) { + metaData.setContentType(contentType); + metaData.setContentDisposition(contentDisposition); + CopyObjectRequest request = (new CopyObjectRequest(bucketName, objectName, bucketName, objectName)).withSourceBucketName(bucketName).withSourceKey(objectName).withNewObjectMetadata(metaData); + + try { + this.s3Client.copyObject(request); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + } + + public void delete(Object... paths) { + List lists = this.list(paths); + lists.forEach((s3Object) -> this.s3Client.deleteObject(this.getBucketName(), s3Object)); + } + + public static Map getRegions() { + Map regions = new HashMap(); + + for(Regions region : Regions.values()) { + regions.put(region.getName(), region.getDescription()); + } + + return regions; + } + + public List list(Object... paths) { + if (this.s3Client == null) { + return null; + } else { + String prefix = this.generateObjectKey(paths); + ObjectListing listing = this.s3Client.listObjects(this.getBucketName(), prefix); + if (listing == null) { + return null; + } else { + List keys = new ArrayList(); + + for(S3ObjectSummary s3Object : listing.getObjectSummaries()) { + keys.add(s3Object.getKey()); + } + + return keys; + } + } + } + + public boolean exists(Object... paths) { + return this.s3Client == null ? false : this.s3Client.doesObjectExist(this.getBucketName(), this.generateObjectKey(paths)); + } + + public void refreshClient() { + boolean hasChange = false; + String accessKey = this.settingsService.get("aws.s3.accessKey"); + if (Strings.isNullOrEmpty(accessKey)) { + this.s3Client = null; + } else { + if (!accessKey.equals(this.accessKey)) { + this.accessKey = accessKey; + hasChange = true; + } + + String secretKey = this.settingsService.get("aws.s3.secret"); + if (Strings.isNullOrEmpty(secretKey)) { + this.s3Client = null; + } else { + if (!secretKey.equals(this.secretKey)) { + this.secretKey = secretKey; + hasChange = true; + } + + String region = this.settingsService.get("aws.s3.region"); + if (Strings.isNullOrEmpty(region)) { + this.s3Client = null; + } else { + if (!region.equals(this.region)) { + this.region = region; + hasChange = true; + } + + if (hasChange) { + AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard(); + if (!Strings.isNullOrEmpty(accessKey)) { + builder.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))); + } + + if (!Strings.isNullOrEmpty(region)) { + Regions regions = Regions.DEFAULT_REGION; + + try { + regions = Regions.fromName(region); + } catch (Exception var9) { + } + + builder.withRegion(regions); + } + + try { + this.s3Client = (AmazonS3)builder.build(); + } catch (Exception ex) { + ex.printStackTrace(); + this.s3Client = null; + } + + } + } + } + } + } + + private String getBucketName() { + return this.settingsService.get("aws.s3.bucket"); + } + + public String getPrefix() { + return this.settingsService.get("aws.s3.prefix"); + } +} diff --git a/src/main/java/com/midm/service/cloudStorage/AzureBlob.java b/src/main/java/com/midm/service/cloudStorage/AzureBlob.java new file mode 100644 index 0000000..659b27d --- /dev/null +++ b/src/main/java/com/midm/service/cloudStorage/AzureBlob.java @@ -0,0 +1,133 @@ +package com.midm.service.cloudStorage; + +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobContainerClient; +import com.azure.storage.blob.BlobServiceClient; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.sas.BlobContainerSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; +import com.azure.storage.common.sas.SasProtocol; +import com.google.common.base.Strings; +import com.midm.service.system.SettingsService; +import com.mitac.cell.internet.http.McHttpClient; +import java.io.File; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; + +public class AzureBlob extends CloudStorage { + private static final String PROPERTY_ACCOUNT_NAME = "azure.blob.account_name"; + private static final String PROPERTY_ACCOUNT_KEY = "azure.blob.account_key"; + private static final String PROPERTY_ENDPOINT_SUFFIX = "azure.blob.endpoint"; + private static final String DEFAULT_ENDPOINT = "core.windows.net"; + private static final String PROPERTY_PROTOCOL = "azure.blob.protocol"; + private static final String DEFAULT_PROTOCOL = "https"; + private static final String PROPERTY_CONTAINER = "azure.blob.container"; + private static final String PROPERTY_PREFIX = "azure.blob.prefix"; + private String connectionString = ""; + private BlobServiceClient serviceClient; + + public AzureBlob(SettingsService settingsService) { + super(settingsService); + this.connectionString = String.format("DefaultEndpointsProtocol=%s;AccountName=%s;AccountKey=%s;EndpointSuffix=%s", settingsService.get("azure.blob.protocol", "https"), settingsService.get("azure.blob.account_name"), settingsService.get("azure.blob.account_key"), settingsService.get("azure.blob.endpoint", "core.windows.net")); + this.refreshClient(); + } + + public String getUrl(Object... paths) { + BlobClient blobClient = this.getBlobClient(paths); + String sasToken = this.getSasToken(blobClient); + return blobClient == null ? null : String.format("%s?%s", blobClient.getBlobUrl(), sasToken); + } + + private String getSasToken(BlobClient blobClient) { + BlobContainerSasPermission blobContainerSasPermission = (new BlobContainerSasPermission()).setReadPermission(true).setWritePermission(true).setListPermission(true); + BlobServiceSasSignatureValues values = (new BlobServiceSasSignatureValues(OffsetDateTime.now().plusDays(7L), blobContainerSasPermission)).setProtocol(SasProtocol.HTTPS_ONLY); + return blobClient.generateSas(values); + } + + public boolean upload(File file, String orgFileName, String contentType, Object... paths) { + BlobClient blobClient = this.getBlobClient(paths); + if (blobClient != null) { + blobClient.uploadFromFile(file.getPath()); + this.setMetaData(blobClient, orgFileName, contentType); + return true; + } else { + return false; + } + } + + public void delete(Object... paths) { + BlobClient blobClient = this.getBlobClient(paths); + if (blobClient.exists()) { + blobClient.delete(); + } + + } + + private BlobClient getBlobClient(Object... paths) { + BlobContainerClient client = this.getContainerClient(); + return client == null ? null : client.getBlobClient(this.generateObjectKey(paths)); + } + + public BlobContainerClient getContainerClient() { + String container = this.settingsService.get("azure.blob.container"); + if (Strings.isNullOrEmpty(container)) { + return null; + } else { + if (this.serviceClient == null) { + this.refreshClient(); + } + + if (this.serviceClient == null) { + return null; + } else { + BlobContainerClient client = this.serviceClient.getBlobContainerClient(container); + if (!client.exists()) { + client.create(); + } + + return client; + } + } + } + + public void refreshClient() { + this.serviceClient = (new BlobServiceClientBuilder()).connectionString(this.connectionString).buildClient(); + } + + public List list(Object... paths) { + BlobContainerClient client = this.getContainerClient(); + if (client != null) { + List items = new ArrayList(); + client.listBlobs().forEach((blobItem) -> items.add(blobItem.getName())); + return items; + } else { + return null; + } + } + + public boolean exists(Object... paths) { + BlobClient blobClient = this.getBlobClient(paths); + return blobClient == null ? false : blobClient.exists(); + } + + public void updateMetaInfo(String orgFileName, String contentType, Object... paths) { + BlobClient blobClient = this.getBlobClient(paths); + if (blobClient.exists()) { + this.setMetaData(blobClient, orgFileName, contentType); + } + + } + + private void setMetaData(BlobClient blobClient, String fileName, String contentType) { + BlobHttpHeaders headers = new BlobHttpHeaders(); + headers.setContentType(contentType); + headers.setContentDisposition(McHttpClient.toContentDisposition(fileName)); + blobClient.setHttpHeaders(headers); + } + + public String getPrefix() { + return this.settingsService.get("azure.blob.prefix"); + } +} diff --git a/src/main/java/com/midm/service/cloudStorage/CloudStorage.java b/src/main/java/com/midm/service/cloudStorage/CloudStorage.java new file mode 100644 index 0000000..6e3d3be --- /dev/null +++ b/src/main/java/com/midm/service/cloudStorage/CloudStorage.java @@ -0,0 +1,128 @@ +package com.midm.service.cloudStorage; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.midm.service.system.SettingsService; +import java.io.File; +import java.util.Date; +import java.util.List; +import org.joda.time.LocalDateTime; + +/** + * ====================================================================================== + * 多云融合对象存储抽象基类 (CloudStorage) + * ====================================================================================== + * + *

【设计模式:策略模式 (Strategy Pattern)】 + * 1. 业务痛点: + * - 面对全球化跨国部署的移动设备与物联网终端,不同国家和地区的云基础设施要求不同(如北美首选 AWS S3、 + * 欧洲优先 Azure、部分亚太客户使用 Google Cloud Platform)。 + * - 若业务代码直接耦合具体的云 SDK,会导致大量重复分支逻辑且难以扩展。 + * 2. 解决方案: + * - 定义统一的对象存储标准抽象基类,规范大文件上传、安全预签名 URL 获取、防盗链过期时间、元数据更新等核心接口。 + * - 子类分别实现 AWS S3 ({@link AwsS3})、微软 Azure Blob ({@link AzureBlob})、谷歌云存储 ({@link GoogleCloudStorage})。 + * + * @author MiDM Core Platform Team + */ +public abstract class CloudStorage { + + /** 预签名下载链接默认有效期:7 天 */ + public static final int LINK_EXPIRY = 7; + + /** 系统动态配置服务(用于读取各大云厂商的 AccessKey, SecretKey, Bucket 等) */ + protected SettingsService settingsService; + + /** + * 构造函数,注入系统配置服务 + * + * @param settingsService 配置服务 + */ + public CloudStorage(SettingsService settingsService) { + this.settingsService = settingsService; + } + + /** + * 生成规范化的多级对象键路径(Object Key),自动拼接云端命名空间前缀 + * + * @param paths 路径分段(如租户 UUID、文件分类、文件名等) + * @return 格式化后的完整对象路径字符串(如 "midm-tenant-1/ota/update.zip") + */ + protected String generateObjectKey(Object... paths) { + String prefix = this.getPrefix(); + return Joiner.on("/").skipNulls().join(Strings.isNullOrEmpty(prefix) ? null : prefix, (Object)null, paths); + } + + /** + * 获取预签名下载链接的默认过期时间点 + * + * @return 当前时间顺延 7 天的 Date 实例 + */ + public Date getUrlExpiry() { + return LocalDateTime.now().plusDays(7).toDate(); + } + + /** + * 获取经过防盗链签名的临时下载 URL(Presigned URL) + *

【架构亮点】受控终端直接通过该安全链接从云厂商 CDN 下载 1~2GB 的 OTA 固件, + * 完全避开业务应用服务器充当流量中转,降低服务器带宽与负载。 + * + * @param paths 对象分级路径 + * @return 带鉴权签名的下载地址 + */ + public abstract String getUrl(Object... paths); + + /** + * 检查远程存储桶中是否存在指定对象 + * + * @param paths 对象分级路径 + * @return true 表示文件存在 + */ + public abstract boolean exists(Object... paths); + + /** + * 列出指定前缀下的所有存储对象 + * + * @param paths 路径前缀 + * @return 对象列表 + */ + public abstract List list(Object... paths); + + /** + * 上传本地文件到云存储 + * + * @param file 本地待上传的临时文件 + * @param orgFileName 原始文件名称(包含扩展名) + * @param contentType 文件的 MIME 类型(如 application/zip, application/vnd.android.package-archive) + * @param paths 云端目标对象路径分段 + * @return true 表示上传成功 + */ + public abstract boolean upload(File file, String orgFileName, String contentType, Object... paths); + + /** + * 删除云端指定对象 + * + * @param paths 对象路径 + */ + public abstract void delete(Object... paths); + + /** + * 刷新并重新初始化云存储 SDK 客户端连接池(当密钥或配置变更时触发) + */ + public abstract void refreshClient(); + + /** + * 更新云端对象的元数据信息(如 Content-Disposition 附件下载名称等) + * + * @param orgFileName 原始文件名 + * @param contentType MIME 类型 + * @param paths 目标路径 + */ + public abstract void updateMetaInfo(String orgFileName, String contentType, Object... paths); + + /** + * 获取当前云存储租户的专属前缀(Namespace Prefix) + * + * @return 命名空间前缀字符串 + */ + public abstract String getPrefix(); +} diff --git a/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java b/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java new file mode 100644 index 0000000..b561ab3 --- /dev/null +++ b/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java @@ -0,0 +1,166 @@ +package com.midm.service.cloudStorage; + +import com.google.common.base.Strings; +import com.midm.service.system.SettingsService; +import java.io.File; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * ====================================================================================== + * 多云存储统一门面服务 (CloudStorageService) + * ====================================================================================== + * + *

【设计模式:门面模式 (Facade Pattern) + 策略上下文 (Strategy Context)】 + * 1. 作为业务层(如应用上传、OTA固件分发、设备日志归档)调用对象存储的统一门面。 + * 2. 动态路由与热切换({@link #refresh()}): + * - 读取系统动态配置项 `cloud.storage`; + * - 运行时支持在 "aws_s3"、"azure_blob"、"google_cloud" 之间平滑切换策略实现,无需重启系统服务。 + * 3. 磁盘空间保护机制: + * - 在将大型 APK 或系统固件镜像成功上传至云存储后,若未开启 `files.keepInLocal`, + * 自动异步删除应用服务器上的本地临时文件,彻底杜绝服务器磁盘空间爆满隐患。 + * + * @author MiDM Core Platform Team + */ +@Service +public class CloudStorageService { + + @Autowired + protected SettingsService settingsService; + + /** 当前生效的云存储策略实例(动态多态绑定) */ + private CloudStorage cloudStorage; + + /** + * 检查当前系统是否已配置并激活云存储服务 + * + * @return true 表示云存储可用;false 表示仅使用本地磁盘 + */ + public boolean hasCloudStorage() { + return this.cloudStorage != null; + } + + /** + * 判定上传后是否需要在本地保留一份文件副本 + * + * @return 若未启用云存储则强制保存在本地;若已启用云存储,则遵循配置项 files.keepInLocal (默认 false) + */ + public boolean keepInLocal() { + return this.hasCloudStorage() ? this.settingsService.getBoolean("files.keepInLocal", false) : true; + } + + /** + * 获取当前底层的具体云存储实现实例 + */ + public CloudStorage getCloudStorage() { + return this.cloudStorage; + } + + /** + * 显式指定云存储策略实例(单元测试或外部注入使用) + */ + public void setCloudStorage(CloudStorage cloudStorage) { + this.cloudStorage = cloudStorage; + } + + /** + * 生成带时效鉴权的客户端下载 URL + * + * @param paths 路径层次结构 + * @return 可供终端直连下载的安全外链 + */ + public String getUrl(Object... paths) { + return this.hasCloudStorage() ? this.cloudStorage.getUrl(paths) : null; + } + + /** + * 校验云端文件是否存在 + */ + public boolean exists(Object... paths) { + return this.hasCloudStorage() ? this.cloudStorage.exists(paths) : false; + } + + /** + * 获取文件列表 + */ + public List list() { + return this.cloudStorage == null ? null : this.cloudStorage.list(); + } + + /** + * 【核心上传方法】将文件上传至对象存储,并按策略管理本地缓存生命周期 + * + * @param file 待上传的文件句柄 + * @param orgFileName 原始文件全名 + * @param contentType 文件的 HTTP Content-Type + * @param paths 远程云存储目标分层路径 + */ + public void upload(File file, String orgFileName, String contentType, Object... paths) { + if (file.exists() && this.cloudStorage != null) { + // 1. 调用底层云策略实现上传 + this.cloudStorage.upload(file, orgFileName, contentType, paths); + + // 2. 磁盘保护:若未配置本地保留,上传成功后立即删除服务器临时缓存 + if (!this.keepInLocal()) { + file.delete(); + } + } + } + + /** + * 从云端删除指定路径的文件 + */ + public void delete(Object... paths) { + if (this.cloudStorage != null) { + this.cloudStorage.delete(paths); + } + } + + /** + * 【动态热切换核心实现】根据系统参数动态实例化或刷新云存储适配器 + * + *

支持在系统运行态无缝变更云存储提供商(AWS S3 / Azure / GCP),并自动重建客户端长连接池。 + */ + public void refresh() { + String cloud = this.settingsService.get("cloud.storage"); + if (!Strings.isNullOrEmpty(cloud)) { + switch (cloud) { + case "aws_s3": + // 切换至 AWS S3 适配器 + if (this.cloudStorage == null || !(this.cloudStorage instanceof AwsS3)) { + this.cloudStorage = new AwsS3(this.settingsService); + } + break; + case "azure_blob": + // 切换至微软 Azure Blob 适配器 + if (this.cloudStorage == null || !(this.cloudStorage instanceof AzureBlob)) { + this.cloudStorage = new AzureBlob(this.settingsService); + } + break; + case "google_cloud": + // 切换至谷歌云存储 GCS 适配器 + if (this.cloudStorage == null || !(this.cloudStorage instanceof GoogleCloudStorage)) { + this.cloudStorage = new GoogleCloudStorage(this.settingsService); + } + break; + default: + this.cloudStorage = null; + } + + // 触发底层 SDK 客户端连接池初始化与参数热加载 + if (this.cloudStorage != null) { + this.cloudStorage.refreshClient(); + } + } + } + + /** + * 更新云端对象的元数据属性 + */ + public void updateMetaInfo(String fileName, String contentType, Object... paths) { + if (this.cloudStorage != null) { + this.cloudStorage.updateMetaInfo(fileName, contentType, paths); + } + } +} diff --git a/src/main/java/com/midm/service/cloudStorage/GoogleCloudStorage.java b/src/main/java/com/midm/service/cloudStorage/GoogleCloudStorage.java new file mode 100644 index 0000000..af4b99b --- /dev/null +++ b/src/main/java/com/midm/service/cloudStorage/GoogleCloudStorage.java @@ -0,0 +1,121 @@ +package com.midm.service.cloudStorage; + +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.BlobId; +import com.google.cloud.storage.BlobInfo; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.common.base.Strings; +import com.midm.service.system.SettingsService; +import com.mitac.cell.internet.http.McHttpClient; +import com.mitac.cell.io.McFile; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +public class GoogleCloudStorage extends CloudStorage { + private static final String PROPERTY_PROJECT_ID = "google.cloud.projectId"; + private static final String PROPERTY_CREDENTIAL = "google.cloud.credential"; + private static final String PROPERTY_BUCKET = "google.cloud.bucket"; + private static final String PROPERTY_PREFIX = "google.cloud.prefix"; + private String projectId = ""; + private String credential = ""; + protected Storage storage; + + public GoogleCloudStorage(SettingsService settingsService) { + super(settingsService); + this.refreshClient(); + } + + public String getUrl(Object... paths) { + BlobId blobId = this.getBlobId(paths); + return blobId == null ? null : blobId.toGsUtilUri(); + } + + public boolean upload(File file, String orgFileName, String contentType, Object... paths) { + BlobId blobId = this.getBlobId(paths); + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentDisposition(McHttpClient.toContentDisposition(orgFileName)).setContentType(contentType).build(); + Blob blob = this.storage.create(blobInfo, new Storage.BlobTargetOption[0]); + + try { + blob.writer(new Storage.BlobWriteOption[0]).write(ByteBuffer.wrap((new McFile(file)).toBytes())); + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + public void delete(Object... paths) { + if (this.storage != null) { + BlobId blobId = this.getBlobId(paths); + this.storage.delete(blobId); + } + + } + + private String getBucketName() { + return this.settingsService.get("google.cloud.bucket"); + } + + public void refreshClient() { + String projectId = this.settingsService.get("google.cloud.projectId"); + if (Strings.isNullOrEmpty(projectId)) { + this.storage = null; + } else { + String credential = this.settingsService.get("google.cloud.credential"); + if (!projectId.equals(this.projectId) || !this.credential.equals(credential)) { + try { + StorageOptions.Builder builder = (StorageOptions.Builder)StorageOptions.newBuilder().setProjectId(projectId); + if (Strings.isNullOrEmpty(credential)) { + GoogleCredentials credentials = GoogleCredentials.fromStream(new ByteArrayInputStream(credential.getBytes())); + builder.setCredentials(credentials); + } + + this.storage = (Storage)builder.build().getService(); + } catch (IOException var5) { + this.storage = null; + } + } + } + + if (this.storage == null) { + this.projectId = ""; + this.credential = ""; + } + + } + + public List list(Object... paths) { + List lists = this.storage.get(new BlobId[]{this.getBlobId(paths)}); + List names = new ArrayList(); + lists.forEach((blob) -> names.add(blob.getName())); + return names; + } + + public boolean exists(Object... paths) { + BlobId blobId = this.getBlobId(paths); + return this.storage.get(blobId).exists(new Blob.BlobSourceOption[0]); + } + + public void updateMetaInfo(String orgFileName, String contentType, Object... paths) { + BlobId blobId = this.getBlobId(paths); + Blob blob = this.storage.get(blobId); + if (blob.exists(new Blob.BlobSourceOption[0])) { + blob.toBuilder().setContentType(contentType).setContentDisposition(McHttpClient.toContentDisposition(orgFileName)).build().update(new Storage.BlobTargetOption[0]); + } + + } + + private BlobId getBlobId(Object... paths) { + return BlobId.of(this.getBucketName(), this.generateObjectKey(paths)); + } + + public String getPrefix() { + return this.settingsService.get("google.cloud.prefix"); + } +} diff --git a/src/main/java/com/midm/service/device/DeviceAppsService.java b/src/main/java/com/midm/service/device/DeviceAppsService.java new file mode 100644 index 0000000..47d68c0 --- /dev/null +++ b/src/main/java/com/midm/service/device/DeviceAppsService.java @@ -0,0 +1,164 @@ +package com.midm.service.device; + +import com.google.common.base.Strings; +import com.midm.model.device.AppInfo; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceApps; +import com.midm.model.file.AppFile; +import com.midm.service.BaseService; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import org.bson.Document; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +@Service +public class DeviceAppsService extends BaseService { + private Map appsMap = new ConcurrentHashMap(); + + public DeviceApps save(DeviceApps apps) { + apps.fixAbnormal(); + UUID deviceUuid = apps.getDeviceUuid(); + DeviceApps prevApps = this.getInstalledApps(deviceUuid); + if (prevApps != null && prevApps.equals(apps)) { + return apps; + } else { + apps = (DeviceApps)this.saveDocument(apps); + if (apps.getCategory().equals("installed")) { + this.appsMap.put(deviceUuid, apps); + } + + return apps; + } + } + + public DeviceApps save(UUID deviceUuid, List apps) { + if (apps != null && !apps.isEmpty()) { + DeviceApps deviceApps = new DeviceApps(); + deviceApps.setDeviceUuid(deviceUuid); + deviceApps.setApps(apps); + return this.save(deviceApps); + } else { + return null; + } + } + + public DeviceApps getInstalledApps(UUID deviceUuid) { + if (this.appsMap.containsKey(deviceUuid)) { + return (DeviceApps)this.appsMap.get(deviceUuid); + } else { + DeviceApps deviceApps = this.getApps(deviceUuid, "installed"); + if (deviceApps != null) { + this.appsMap.put(deviceUuid, deviceApps); + } + + return deviceApps; + } + } + + public DeviceApps getApps(UUID deviceUuid, String category) { + Query query = this.queryByIdAndCategory(deviceUuid, category); + DeviceApps deviceApps = (DeviceApps)this.mongoTemplate.findOne(query, DeviceApps.class); + return deviceApps; + } + + public Document installedApp(Device device, String packageName, int versionCode, String versionName, int minSdk) { + Document document = (new Document("deviceUuid", device.getUuid())).append("packageName", packageName); + DeviceApps apps = this.getInstalledApps(device.getUuid()); + AppInfo appInfo = apps.getApp(packageName); + if (appInfo != null) { + document.append("versionCode", appInfo.getVersionCode()); + document.append("versionName", appInfo.getVersionName()); + } else { + document.append("versionCode", versionCode); + document.append("versionName", versionName); + } + + boolean installed = apps != null && apps.isAppInstalled(device.getSdkVersion(), packageName, (long)versionCode, minSdk); + document.append("installed", installed); + return document; + } + + public boolean hasInstalledApps(UUID deviceUuid) { + if (!this.appsMap.containsKey(deviceUuid)) { + Query query = this.queryByIdAndCategory(deviceUuid, "installed"); + return this.mongoTemplate.exists(query, DeviceApps.class); + } else { + return true; + } + } + + private Query queryByIdAndCategory(UUID deviceUuid, String category) { + return Query.query(Criteria.where("_id").is(deviceUuid).and("category").is(category)); + } + + public boolean newClientAppInstalled(UUID deviceUuid) { + DeviceApps apps = this.getInstalledApps(deviceUuid); + if (apps == null) { + return false; + } else { + AppInfo appInfo = apps.getClientService(); + if (appInfo == null) { + return false; + } else { + int versionCode = appInfo.getVersionCode(); + return versionCode >= 1030 || versionCode < 1000 && versionCode > 220; + } + } + } + + public DeviceApps updateDeviceAppState(UUID deviceUuid, String packageName, int versionCode, String versionName, String label) { + DeviceApps apps = this.getInstalledApps(deviceUuid); + if (apps != null) { + AppInfo appInfo = apps.getApp(packageName); + if (appInfo != null && appInfo.getVersionCode() == versionCode) { + return apps; + } + } else { + apps = new DeviceApps(); + apps.setDeviceUuid(deviceUuid); + } + + AppInfo appInfo = apps.getApp(packageName); + if (appInfo == null) { + appInfo = new AppInfo(); + appInfo.setPackageName(packageName); + appInfo.setFirstInstalled((new Date()).getTime()); + if (Strings.isNullOrEmpty(label)) { + Query query = Query.query(Criteria.where("appInfo.packageName").is(packageName)); + AppFile appFile = (AppFile)this.mongoTemplate.findOne(query, AppFile.class); + if (appFile != null) { + appInfo.setLabel(appFile.getLabel()); + } + } + + apps.setApp(appInfo); + } + + appInfo.setVersionCode(versionCode); + appInfo.setVersionName(versionName); + appInfo.setLastUpdated((new Date()).getTime()); + this.mongoTemplate.updateFirst(this.queryByIdAndCategory(deviceUuid, "installed"), Update.update("apps", apps.getApps()), DeviceApps.class); + return apps; + } + + public void removeDeviceApp(UUID deviceUuid, String packageName) { + Update update = new Update(); + update.pull("apps", new Document("packageName", packageName)); + this.mongoTemplate.updateMulti(this.queryById(deviceUuid), update, DeviceApps.class); + } + + public void delete(UUID deviceUuid) { + this.deleteById(DeviceApps.class, deviceUuid); + this.appsMap.remove(deviceUuid); + } + + public void removeCache(UUID deviceUuid) { + this.appsMap.remove(deviceUuid); + } +} diff --git a/src/main/java/com/midm/service/device/DeviceKeyService.java b/src/main/java/com/midm/service/device/DeviceKeyService.java new file mode 100644 index 0000000..5e3e216 --- /dev/null +++ b/src/main/java/com/midm/service/device/DeviceKeyService.java @@ -0,0 +1,164 @@ +package com.midm.service.device; + +import com.google.common.base.Strings; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceKey; +import com.midm.service.BaseService; +import com.midm.service.ExternalApiService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.utils.McCipherUtils; +import java.util.HashMap; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.util.Pair; +import org.springframework.stereotype.Service; + +/** + * ====================================================================================== + * 终端设备非对称加密秘钥与硬件身份鉴权服务 (DeviceKeyService) + * ====================================================================================== + * + *

【物联网端侧安全核心亮点】 + * 1. 业务痛点与防伪造: + * - 在公共移动蜂窝网络下,恶意攻击者可能会伪造出厂序列号(SerialNo / IMEI) + * 假冒企业设备接入云平台窃取策略配置或分发恶意软件。 + * 2. 【双向认证与 RSA-OAEP 非对称验签】: + * - 终端在出厂固化或首次安全绑定时生成 RSA 密钥对,私钥(Private Key)存储于云端安全数据库; + * - 终端发起核心控制请求时,携带用设备端公钥加密的身份密文串; + * - 云端采用标准高级加密填充标准 `RSA/ECB/OAEPWithSHA-1AndMGF1Padding` 解密校验, + * 比对解密后的内容是否严格匹配其硬件序列号,实现硬件级防篡改与防重放。 + * 3. 【多级性能缓存设计】: + * - 维护进程内内存缓存 `keyBySerailNo`,配合同步锁(synchronized)避免高并发请求下频繁穿透查询 MongoDB。 + * + * @author MiDM Core Platform Team + */ +@Service +public class DeviceKeyService extends BaseService { + + /** 线程安全互斥锁对象,防止并发更新内存缓存产生竞态条件 */ + private static Object lock = new Object(); + + /** 内存高频读缓存:以设备序列号为 Key,加速高频接口的非对称密钥提取 */ + private static Map keyBySerailNo = new HashMap(); + + @Autowired + DeviceService deviceService; + + @Autowired + SettingsService settingsService; + + /** + * 保存或更新设备的 RSA 秘钥档案 + * + * @param serialNo 设备唯一硬件序列号 + * @param rsa PEM 格式私钥文本 + * @return 存储的 DeviceKey 实体 + */ + public DeviceKey save(String serialNo, String rsa) { + if (rsa != null) { + // 去除 PEM 格式头尾标记与换行符,提取纯 Base64 私钥密文 + rsa = rsa.trim().replace("\n", "").replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", ""); + } + + DeviceKey existKey = this.findBySerialNo(serialNo); + if (existKey != null) { + existKey.setRsa(rsa); + } else { + existKey = new DeviceKey(serialNo, rsa); + } + + existKey = (DeviceKey)this.saveDocument(existKey); + // 同步刷新本地内存缓存 + keyBySerailNo.put(serialNo, existKey); + return existKey; + } + + /** + * 依据设备实体保存 RSA 私钥 + */ + public DeviceKey save(Device device, String rsa) { + DeviceKey key = null; + if (device != null) { + key = this.save(device.getSerialNo(), rsa); + } + return key; + } + + /** + * 【两级缓存读取】根据序列号获取设备秘钥(优先内存缓存,未命中查 MongoDB) + * + * @param serialNo 序列号 + * @return 秘钥实体 + */ + public DeviceKey findBySerialNo(String serialNo) { + if (Strings.isNullOrEmpty(serialNo)) { + return null; + } else if (keyBySerailNo.containsKey(serialNo)) { + // 1. 命中内存缓存直接返回 + return (DeviceKey)keyBySerailNo.get(serialNo); + } else { + // 2. 缓存未命中,查询 MongoDB + Criteria criteria = Criteria.where("deviceSerial").is(serialNo); + Query query = new Query(criteria); + DeviceKey key = (DeviceKey)this.mongoTemplate.findOne(query, DeviceKey.class); + // 3. 线程安全地回填到内存缓存 + synchronized(lock) { + keyBySerailNo.put(serialNo, key); + return key; + } + } + } + + /** + * 删除设备秘钥档案,并清除本地内存缓存 + */ + public void delete(String serialNo) { + Criteria criteria = Criteria.where("deviceSerial").is(serialNo); + Query query = Query.query(criteria); + this.mongoTemplate.remove(query, DeviceKey.class); + keyBySerailNo.remove(serialNo); + } + + /** + * 【核心安全鉴权算法】校验终端上报的 RSA 密文是否合法 + * + * @param serialNo 声明的硬件序列号 + * @param encryptString 终端携带的加密签名串 + * @return Pair(是否有效 true/false, 错误描述原因) + */ + public Pair isValidRsa(String serialNo, String encryptString) { + // 1. 检查全局是否开启了严格 RSA 硬件鉴权开关 + if (!this.settingsService.rsaEnabled()) { + return Pair.of(true, ""); + } else { + // 2. 若配置了外部专用安全微服务鉴权地址,委托外部安全中心验签 + String urlValidateRsa = this.settingsService.get("url.validate.rsa"); + if (!Strings.isNullOrEmpty(urlValidateRsa)) { + return ExternalApiService.doRequestRsaIsValid(urlValidateRsa, serialNo, encryptString); + } else { + // 3. 本地基于非对称私钥解密校验 + DeviceKey key = this.findBySerialNo(serialNo); + if (key == null) { + return Strings.isNullOrEmpty(encryptString) ? + Pair.of(true, "") : + Pair.of(false, "InvalidRsa, No need to check RSA, but request bear the encryptString"); + } else if (Strings.isNullOrEmpty(encryptString)) { + return Pair.of(false, "InvalidRsa, Device should bear the key"); + } else { + // 4. 使用工业级 OAEP 填充算法解密密文,比对解密结果是否与声明的 serialNo 一致 + boolean isValid = McCipherUtils.decryptByPrivateKey( + "RSA/ECB/OAEPWithSHA-1AndMGF1Padding", + key.getRsa(), + encryptString, + serialNo + ); + return isValid ? + Pair.of(true, "") : + Pair.of(false, "InvalidRsa, Device bear wrong key"); + } + } + } + } +} diff --git a/src/main/java/com/midm/service/device/DeviceReportService.java b/src/main/java/com/midm/service/device/DeviceReportService.java new file mode 100644 index 0000000..9e62ef1 --- /dev/null +++ b/src/main/java/com/midm/service/device/DeviceReportService.java @@ -0,0 +1,772 @@ +package com.midm.service.device; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.midm.model.device.AppInfo; +import com.midm.model.device.DataUsage; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceApps; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.DeviceProfileState; +import com.midm.model.device.DeviceReport; +import com.midm.model.file.AppFile; +import com.midm.model.file.OtaFile; +import com.midm.model.log.MidmLog; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.ExternalApiService; +import com.midm.service.file.FileService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.SiteService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McJsonUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.UUID; +import java.util.concurrent.ScheduledFuture; +import org.bson.Document; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.BulkOperations; +import org.springframework.data.mongodb.core.BulkOperations.BulkMode; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.SortOperation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; + +@Service +public class DeviceReportService extends BaseService { + private static final long MIN_DATA_USAGE_GAP = 900000L; + @Autowired + @Lazy + private SiteService siteService; + @Autowired + @Lazy + private DeviceService deviceService; + @Autowired + @Lazy + private ProfileService profileService; + @Autowired + @Lazy + private FileService fileService; + @Autowired + @Lazy + private DeviceAppsService deviceAppsService; + @Autowired + @Lazy + private SettingsService settingsService; + @Autowired + @Lazy + private WebSocketSessionManager sessionManager; + @Autowired + @Qualifier("stringTemplateEngine") + private TemplateEngine stringTemplateEngine; + private Map profileNotifySchedules = new HashMap(); + private Map profileStateUpdateSchedules = new HashMap(); + private Map dataUsageSchedules = new HashMap(); + private Map dataUsageMap = new HashMap(); + + public DeviceReport save(DeviceReport report) { + if (report.getDeviceUuid() == null) { + return report; + } else { + if (report.getUuid() == null) { + report.setUuid(UUID.randomUUID()); + } + + if (report.getReportedAt() == null) { + report.setReportedAt(new Date()); + } + + try { + return (DeviceReport)this.saveDocument(report); + } catch (Exception var3) { + return null; + } + } + } + + public Collection save(UUID siteUuid, Collection reports) { + Collection reportedList = null; + + try { + reportedList = this.mongoTemplate.insertAll(reports); + } catch (Exception var8) { + reportedList = new ArrayList(); + + for(DeviceReport report : reports) { + DeviceReport savedReport = this.save(report); + if (savedReport != null) { + reportedList.add(report); + } + } + } + + this.requestCallbackApi(siteUuid, reportedList); + return reportedList; + } + + public DeviceReport save(Device device, String item, Object content) { + DeviceReport report = new DeviceReport(); + report.init(); + report.setDeviceUuid(device.getUuid()); + report.setSerialNo(device.getSerialNo()); + report.setProperty(item, content); + report = this.save(report); + this.requestCallbackApi(device.getSiteUuid(), (Collection)Arrays.asList(report)); + return report; + } + + public void requestToApplyOtaFirst(Device device) { + List profiles = this.profileService.findAllByDevice(device, false, true, false); + if (profiles != null && !profiles.isEmpty()) { + profiles.forEach((profile) -> { + String applyOrder = profile.applyOrder(); + if (!Strings.isNullOrEmpty(applyOrder) && applyOrder.equals("otas")) { + List otas = profile.getOtas(); + if (otas != null && !otas.isEmpty()) { + DeviceProfileState profileState = this.getProfileState(device.getUuid(), profile); + if (profileState != null) { + String applyFirstState = profileState.getApplyFirstState(); + if (!Strings.isNullOrEmpty(applyFirstState) && applyFirstState.equals("in_progress")) { + this.notifyUpdateProfile(device, profile, 1); + } + } + } + } + + }); + } + } + + public void updateDeviceProfileState(DeviceProfileState curState, DeviceProfile profileReference) { + UUID profileUuid = curState.getProfileUuid(); + DeviceProfile profile = profileReference != null ? profileReference : this.profileService.find(profileUuid, true); + if (profile != null && profile.getEnabled() && !profile.isEnded()) { + UUID deviceUuid = curState.getDeviceUuid(); + DeviceProfileState prevState = this.getProfileState(deviceUuid, profile); + if (prevState == null || prevState.getApplied() < curState.getApplied()) { + long reportUpdated = curState.getUpdated(); + long orgUpdated = profile.getUpdated().getTime(); + boolean isSameProfile = reportUpdated == orgUpdated; + boolean isApplyFirstReport = reportUpdated == orgUpdated - 1L; + Device device = (Device)this.deviceService.findById(Device.class, deviceUuid); + if (device != null) { + boolean isAppsApplied = this.profileService.isAllAppsInstalled(profile, device); + boolean isOtaApplied = this.profileService.isAllOtasInstalled(profile, device); + boolean isProfileApplied = isAppsApplied && isOtaApplied; + int notifyAfter = -1; + String applyOrder = profile.applyOrder(); + if (!isSameProfile && !applyOrder.equals("none")) { + if (!isApplyFirstReport) { + return; + } + + curState.setUpdated(orgUpdated); + notifyAfter = 60; + switch (applyOrder) { + case "settings": + curState.setApplyFirstState("done"); + curState.setState("in_progress"); + break; + case "apps": + if (!isAppsApplied) { + curState.setApplyFirstState("in_progress"); + curState.setState("in_progress"); + this.sessionManager.updateInstalledApps(deviceUuid); + notifyAfter = 120; + } else { + curState.setApplyFirstState("done"); + curState.setState("in_progress"); + } + break; + case "otas": + if (!isOtaApplied) { + curState.setApplyFirstState("in_progress"); + curState.setState("in_progress"); + notifyAfter = 180; + } else { + curState.setApplyFirstState("done"); + curState.setState("in_progress"); + } + } + } else { + curState.setState(isProfileApplied ? "done" : "in_progress"); + if (!isOtaApplied) { + notifyAfter = 180; + } else if (!isAppsApplied) { + notifyAfter = 120; + } + } + + if (prevState == null || !prevState.isDone()) { + curState = this.saveDocument(curState); + } + + this.logProfileState(curState, profileUuid, profile.getName(), applyOrder, isApplyFirstReport); + if (curState.isDone() && isProfileApplied) { + if (profile.unscopeIfApplied()) { + this.profileService.unscope(profile, device.getSerialNo()); + } + + this.requestCallbackApi(device.getSiteUuid(), curState.getReport()); + if (profile.hasSequence()) { + List sequences = profile.getSequence(); + Iterator sequenceIt = sequences.iterator(); + boolean found = false; + + while(sequenceIt.hasNext()) { + UUID sequencedUuid = (UUID)sequenceIt.next(); + if (found) { + profile = this.profileService.find(sequencedUuid, true); + if (this.profileService.isDeviceScoped(device, profile) && !this.profileService.isProfileApplied(sequencedUuid, device)) { + notifyAfter = 120; + break; + } + } else if (sequencedUuid.equals(profile.getUuid())) { + found = true; + } + } + } + } + + if (notifyAfter > 0) { + this.notifyUpdateProfile(device, profile, notifyAfter); + } + + } + } + } else { + this.deleteById(DeviceProfileState.class, curState.getScoped()); + } + } + + public void notifyUpdateProfile(Device device, DeviceProfile profile, int notifyAfter) { + String taskId = this.getTaskId(device.getUuid(), profile.getUuid()); + if (this.profileNotifySchedules.containsKey(taskId)) { + ((ScheduledFuture)this.profileNotifySchedules.get(taskId)).cancel(true); + } + + ScheduledFuture scheduledTask = this.schedule(() -> { + this.profileService.notifyUpdate(device, profile, true); + this.profileNotifySchedules.remove(taskId); + }, this.secondsLater(notifyAfter)); + this.profileNotifySchedules.put(taskId, scheduledTask); + } + + public void updateDeviceProfileState(Device device, DeviceProfile profile) { + this.scheduleUpdateProfileState(new DeviceProfileState(device, profile), profile); + } + + public void updateDeviceProfileState(DeviceReport report) { + this.scheduleUpdateProfileState(new DeviceProfileState((DeviceReport)McJsonUtils.clone(report)), (DeviceProfile)null); + } + + public void scheduleUpdateProfileState(DeviceProfileState state, DeviceProfile profile) { + String taskId = this.getTaskId(state.getDeviceUuid(), state.getProfileUuid()); + this.cancelProfileUpdateSchedule(taskId); + ScheduledFuture scheduledTask = this.schedule(() -> { + this.updateDeviceProfileState(state, profile); + this.profileStateUpdateSchedules.remove(taskId); + }, this.secondsLater(5)); + this.profileStateUpdateSchedules.put(taskId, scheduledTask); + } + + private void cancelProfileUpdateSchedule(String taskId) { + if (this.profileStateUpdateSchedules.containsKey(taskId)) { + ((ScheduledFuture)this.profileStateUpdateSchedules.get(taskId)).cancel(true); + } + + } + + private String getTaskId(UUID deviceUuid, UUID profileUuid) { + String var10000 = deviceUuid.toString(); + return var10000 + profileUuid.toString(); + } + + public void stopProfileNotifySchedule(UUID deviceUuid) { + String uuid = deviceUuid.toString(); + this.profileNotifySchedules.keySet().forEach((taskId) -> { + if (taskId.startsWith(uuid)) { + ((ScheduledFuture)this.profileNotifySchedules.get(taskId)).cancel(true); + this.profileNotifySchedules.remove(taskId); + } + + }); + } + + public void updateProfileState(UUID profileUuid, UUID deviceUuid, String state) { + Criteria criteria = Criteria.where("_id.profileUuid").is(profileUuid).and("_id.deviceUuid").is(deviceUuid); + Update update = Update.update("state", state); + this.mongoTemplate.updateFirst(Query.query(criteria), update, DeviceProfileState.class); + } + + private void logProfileState(DeviceProfileState curState, UUID profileUuid, String profileName, String applyOrder, boolean isApplyFirstReport) { + String log = null; + if (curState.isDone()) { + log = String.format("Configuration profile '%s(%s)' has been applied.", profileName, profileUuid); + } else if (isApplyFirstReport) { + if (curState.isApplyFirstDone()) { + log = String.format("Apply first option(%s) of profile '%s(%s)' has been applied.", applyOrder, profileName, profileUuid); + } else { + log = String.format("Apply first option(%s) of profile '%s(%s)' is in progress.", applyOrder, profileName, profileUuid); + } + } else { + log = String.format("Configuration profile '%s(%s)' is in progress.", profileName, profileUuid); + } + + MidmLog stateLog = new MidmLog((User)null, curState.getDeviceUuid(), "update", log); + stateLog.addReference("updated", curState.getUpdated()); + stateLog.setLoggedAt(curState.getApplied()); + this.saveDocument(stateLog); + } + + public List find(UUID deviceUuid, String key, int limit) { + Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid); + if (!Strings.isNullOrEmpty(key)) { + criteria.and(this.propertyName(key)).exists(true); + } + + Sort sort = Sort.by(Direction.DESC, new String[]{"reportedAt"}); + Query query = Query.query(criteria).with(sort).limit(limit); + return this.mongoTemplate.find(query, DeviceReport.class); + } + + public Page find(UUID deviceUuid, String key, Integer page, Integer size, String sortBy, String direction) { + Sort sort = Sort.by(Direction.DESC, new String[]{"reportedAt"}); + Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid).and(this.propertyName(key)).exists(true); + Query query = Query.query(criteria).with(sort); + List reports = this.mongoTemplate.find(query, DeviceReport.class); + Page resultPage = new PageImpl(reports.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, reports.size())), PageRequest.of(page, size), (long)reports.size()); + return resultPage; + } + + public DeviceReport findLatestLocation(UUID deviceUuid) { + Sort sort = Sort.by(Direction.DESC, new String[]{"properties.location.time"}); + Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid).and(this.propertyName("location.latitude")).exists(true); + Query query = Query.query(criteria).with(sort); + return (DeviceReport)this.mongoTemplate.findOne(query, DeviceReport.class); + } + + public List findByDeviceUuidAndLocationExists(UUID deviceUuid, Long from, Long to) { + if (from == null) { + from = 0L; + } + + if (to == null) { + to = (new Date()).getTime(); + } + + String timeField = "properties.location.time"; + Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid).and("properties.location.latitude").exists(true).and("properties.location.time").gte(from).lt(to); + Sort sort = Sort.by(Direction.DESC, new String[]{"properties.location.time"}); + Query query = Query.query(criteria).with(sort); + return this.mongoTemplate.findDistinct(query, "properties.location", DeviceReport.class, Document.class); + } + + public List getDataUsage(Device device, Date from, Date to, McDateTimeUtils.FREQUENCY frequency, String networkType, TimeZone timeZone, boolean separate) { + Document matches = new Document("deviceUuid", device.getUuid()); + Document matchStage = new Document("$match", matches); + AggregationOperation matchOp = Aggregations.newOperation(matchStage); + if (from != null) { + matches.append("from", new Document("$gte", from)); + } + + if (to != null) { + matches.append("to", new Document("$lt", to)); + } + + AggregationOperation sortOp = new SortOperation(Sort.by(Direction.ASC, new String[]{"from"})); + if (Strings.isNullOrEmpty(networkType)) { + networkType = "both"; + } + + Document addFieldStage = new Document(); + Document groupping = new Document("_id", frequency == null ? "$deviceUuid" : new Document("$dateTrunc", (new Document("date", "$to")).append("unit", frequency.name()).append("timezone", timeZone.getID()))); + groupping.append("from", new Document("$first", "$from")); + groupping.append("to", new Document("$last", "$to")); + if (networkType.equalsIgnoreCase("WIFI") || networkType.equalsIgnoreCase("both")) { + if (separate) { + groupping.append("wifi_rx", new Document("$sum", new Document("$sum", "$usage.wifi.rx"))); + groupping.append("wifi_tx", new Document("$sum", new Document("$sum", "$usage.wifi.tx"))); + addFieldStage.append("wifi", (new Document("rx", "$wifi_rx")).append("tx", "$wifi_tx")); + } else { + groupping.append("wifi", new Document("$sum", new Document("$sum", Arrays.asList("$usage.wifi.rx", "$usage.wifi.tx")))); + } + } + + if (networkType.equalsIgnoreCase("MOBILE") || networkType.equalsIgnoreCase("both")) { + if (separate) { + groupping.append("mobile_rx", new Document("$sum", new Document("$sum", "$usage.mobile.rx"))); + groupping.append("mobile_tx", new Document("$sum", new Document("$sum", "$usage.mobile.tx"))); + addFieldStage.append("mobile", (new Document("rx", "$mobile_rx")).append("tx", "$mobile_tx")); + } else { + groupping.append("mobile", new Document("$sum", new Document("$sum", Arrays.asList("$usage.mobile.rx", "$usage.mobile.tx")))); + } + } + + Document groupStage = new Document("$group", groupping); + AggregationOperation groupOp = Aggregations.newOperation(groupStage); + AggregationOperation addFieldOp = Aggregations.newOperation(new Document("$addFields", addFieldStage)); + Document projectStage = (new Document("wifi_rx", 0)).append("wifi_tx", 0).append("mobile_rx", 0).append("mobile_tx", 0); + AggregationOperation projectOp = Aggregations.newOperation(new Document("$project", projectStage)); + List results = this.mongoTemplate.aggregate(Aggregation.newAggregation(new AggregationOperation[]{matchOp, sortOp, groupOp, addFieldOp, projectOp}), DataUsage.class, Document.class).getMappedResults(); + return results.isEmpty() ? null : results; + } + + public boolean canSave(UUID deviceUuid, DataUsage usage) { + if (usage.getFrom().equals(usage.getTo())) { + return false; + } else if (DateTime.now().minusMonths(3).isAfter(usage.getTo().getTime())) { + return false; + } else { + DataUsage latest = this.latestDataUsage(deviceUuid); + if (latest != null && !usage.isLaterThan(latest)) { + List overlapCriterias = Arrays.asList(Criteria.where("from").lte(usage.getFrom()).and("to").gte(usage.getFrom()), Criteria.where("from").lte(usage.getTo()).and("to").gte(usage.getTo())); + Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid).orOperator(overlapCriterias); + Query query = Query.query(criteria); + return !this.mongoTemplate.exists(query, DataUsage.class); + } else { + this.dataUsageMap.put(deviceUuid, usage); + return true; + } + } + } + + private DataUsage latestDataUsage(UUID deviceUuid) { + DataUsage usage; + if (this.dataUsageMap.containsKey(deviceUuid)) { + usage = (DataUsage)this.dataUsageMap.get(deviceUuid); + } else { + Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid); + Query query = Query.query(criteria).with(Sort.by(Direction.DESC, new String[]{"to"})); + usage = (DataUsage)this.mongoTemplate.findOne(query, DataUsage.class); + this.dataUsageMap.put(deviceUuid, usage); + } + + return usage; + } + + public DataUsage saveDataUsage(Device device, DbObject usage) { + DataUsage newUsage = new DataUsage(device, usage); + if (this.canSave(device.getUuid(), newUsage)) { + newUsage = (DataUsage)this.mongoTemplate.save(newUsage); + this.updateMissingDataUsage(device.getUuid(), newUsage); + return newUsage; + } else { + return null; + } + } + + public void updateDataUsage(Device device, Date to) { + UUID deviceUuid = device.getUuid(); + if (this.sessionManager.isOnline(deviceUuid) && !this.dataUsageSchedules.containsKey(deviceUuid)) { + ScheduledFuture scheduledTask = this.schedule(() -> { + this.requestDataUsage(deviceUuid, (DateTime)null, (DateTime)null); + this.dataUsageSchedules.remove(deviceUuid); + }, this.secondsLater(120)); + this.dataUsageSchedules.put(deviceUuid, scheduledTask); + } + } + + @Async + private void updateMissingDataUsage(UUID deviceUuid, DataUsage curUsage) { + DataUsage latest = this.latestDataUsage(deviceUuid); + if (latest != null) { + Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid).and("to").lte(curUsage.getFrom())).with(Sort.by(Direction.DESC, new String[]{"from"})); + DataUsage prevUsage = (DataUsage)this.mongoTemplate.findOne(query, DataUsage.class); + if (prevUsage != null) { + long gap = Math.abs(curUsage.getFrom().getTime() - prevUsage.getTo().getTime()); + if (gap >= 900000L) { + this.requestDataUsage(deviceUuid, (new DateTime(prevUsage.getTo())).plusMillis(1), (new DateTime(curUsage.getFrom())).minusMillis(1)); + } + } + } + } + + private void requestDataUsage(UUID deviceUuid, DateTime fromDate, DateTime toDate) { + DataUsage latest = this.latestDataUsage(deviceUuid); + DateTime toDay = toDate == null ? LocalDate.now().toDateTimeAtStartOfDay() : toDate.withTimeAtStartOfDay(); + DateTime toTime = toDate == null ? toDay.withHourOfDay(DateTime.now().getHourOfDay()) : toDate; + DateTime days30Ago = toDay.minusDays(30); + DateTime yesterday = toDay.minusDays(1); + DateTime from = null; + DateTime to = null; + if (latest != null) { + from = fromDate == null ? new DateTime(latest.getTo()) : fromDate; + if (from.isAfter(toTime.minusHours(1))) { + return; + } + + if (from.isBefore(days30Ago)) { + from = days30Ago; + } else { + DateTime dayFrom = from.toLocalDate().toDateTimeAtStartOfDay(); + to = from.isBefore(yesterday) ? dayFrom.plusDays(1).withTimeAtStartOfDay() : dayFrom.withHourOfDay(from.getHourOfDay()).plusHours(1); + if (!to.isBefore(toTime)) { + this.sessionManager.requestDataUsage(deviceUuid, from, toTime); + return; + } + + this.sessionManager.requestDataUsage(deviceUuid, from, to); + from = to; + } + } else { + from = days30Ago; + } + + while(from.isBefore(yesterday)) { + to = from.plusDays(1); + this.sessionManager.requestDataUsage(deviceUuid, from, to); + from = to; + } + + to = toTime.minusHours(24); + if (from.compareTo(to) <= 0) { + this.sessionManager.requestDataUsage(deviceUuid, from, to); + from = to; + } + + while(from.isBefore(toTime)) { + to = from.plusHours(1); + if (to.isAfter(toTime)) { + to = toTime; + } + + this.sessionManager.requestDataUsage(deviceUuid, from, to); + from = to; + } + + } + + public DeviceProfileState saveDocument(DeviceProfileState state) { + if (state.isDone()) { + state.setApplyFirstState((String)null); + } + + return (DeviceProfileState)super.saveDocument(state); + } + + public boolean isProfileApplied(UUID deviceUuid, UUID profileUuid) { + DeviceProfile deviceProfile = this.profileService.find(profileUuid, true); + return this.isProfileApplied(deviceUuid, deviceProfile); + } + + public boolean isProfileApplied(UUID deviceUuid, DeviceProfile deviceProfile) { + if (deviceProfile == null) { + return false; + } else { + DeviceProfileState state = this.getProfileState(deviceUuid, deviceProfile); + return state != null && state.isDone(); + } + } + + public DeviceProfileState getProfileState(UUID deviceUuid, DeviceProfile deviceProfile) { + if (deviceProfile == null) { + return null; + } else { + Query query = this.stateQuery(deviceUuid, deviceProfile); + return (DeviceProfileState)this.mongoTemplate.findOne(query, DeviceProfileState.class); + } + } + + public String profileProgressToHtmlContent(Device device, UUID profileUuid) { + DbObject progress = this.profileProgress(device, profileUuid); + String progressTemplate = this.fileService.getResourceToString("help/profileProgress.html", false); + Context context = new Context(); + context.setVariable("progress", progress); + return this.stringTemplateEngine.process(progressTemplate, context); + } + + public List profileProgress(Device device) { + List profiles = this.profileService.findAllByDevice(device, false, false, true); + profiles.forEach((profile) -> { + DbObject progress = this.profileProgress(device, profile.getUuid()); + profile.setProgress(progress); + }); + return profiles; + } + + public DbObject profileProgress(Device device, UUID profileUuid) { + DbObject progress = new DbObject(); + UUID deviceUuid = device.getUuid(); + DeviceProfile profile = this.profileService.find(profileUuid, true); + Site site = this.siteService.findByUuid(device.getSiteUuid()); + TimeZone timeZone = site.getTimeZone(); + DeviceProfileState profileState = this.getProfileState(device.getUuid(), profile); + if (profileState == null) { + progress.append("state", "unknown"); + progress.append("updated", profile.getUpdated()); + } else { + progress.append("state", profileState.getState()); + progress.append("updated", new Date(profileState.getUpdated())); + String applied = McDateTimeUtils.toString(new Date(profileState.getApplied()), timeZone, "yyyy-MM-dd HH:mm:ssZZ"); + progress.append("applied", applied); + } + + List appUuids = profile.getInstallUuids(); + Collection apps = this.fileService.findApps(appUuids, (String)null, device.getSdkVersion()); + if (apps != null && !apps.isEmpty()) { + DbObject appProgresses = new DbObject(); + DeviceApps installedApps = this.deviceAppsService.getInstalledApps(deviceUuid); + Iterator it = apps.iterator(); + int installedCount = 0; + + while(it.hasNext()) { + AppFile appFile = (AppFile)it.next(); + String packageName = appFile.getPackageName(); + AppInfo appInfo = installedApps == null ? null : installedApps.getApp(packageName); + boolean isInstalled = appInfo != null && (long)appInfo.getVersionCode() >= appFile.getVersionCode(); + if (isInstalled) { + ++installedCount; + } + + Document appProgress = (new DbObject("label", appFile.getLabel())).append("versionCode", appFile.getVersionCode()).append("versionName", appFile.getVersionName()); + Document state = new Document("isInstalled", isInstalled); + if (appInfo != null) { + state.append("versionCode", appInfo.getVersionCode()).append("versionName", appInfo.getVersionName()); + } + + appProgress.append("state", state); + appProgresses.put(packageName, appProgress); + } + + if (!appProgresses.isEmpty()) { + progress.put("apps", (new Document("state", appProgresses)).append("progress", (new Document("total", apps.size())).append("installed", installedCount).append("percent", (float)installedCount / (float)apps.size()))); + } + } + + List otaUuids = profile.getOtas(); + if (otaUuids != null && !otaUuids.isEmpty()) { + List otaFiles = this.fileService.findOtas(otaUuids); + if (otaFiles.size() > 2) { + Collections.sort(otaFiles); + } + + Iterator it = otaFiles.iterator(); + OtaFile targetSystem = null; + OtaFile targetRegion = null; + + while(it.hasNext()) { + OtaFile otaFile = (OtaFile)it.next(); + if (otaFile.getDeviceId().equals(device.getDeviceId())) { + if (otaFile.isSystemImage()) { + if (otaFile.getSkuId().equals(device.getSkuId()) && (targetSystem == null || targetSystem.getBuildDate() < otaFile.getBuildDate())) { + targetSystem = otaFile; + } + } else if (otaFile.getCustomerId().equals(device.getCustomerId()) && (targetRegion == null || targetRegion.getScriptVersion().equals(otaFile.getScriptVersion()))) { + targetRegion = otaFile; + } + } + } + + Document otaProgresses = new Document(); + if (targetSystem != null) { + Document systemProgress = (new Document("isInstalled", targetSystem.getBuildDate() <= device.getBuildDate())).append("buildNo", targetSystem.getDisplayId()).append("curBuildNo", device.getBuildNo()); + otaProgresses.put("system", systemProgress); + } + + if (targetRegion != null) { + Document regionProgress = (new Document("isInstalled", targetRegion.getScriptVersion().equals(device.getScriptVersion()))).append("scriptVersion", targetRegion.getScriptVersion()).append("curScriptVersion", device.getScriptVersion()); + otaProgresses.put("region", regionProgress); + } + + if (!otaProgresses.isEmpty()) { + progress.put("otas", otaProgresses); + } + } + + return progress; + } + + public void resetProfile(UUID profileUuid) { + Criteria criteria = Criteria.where("_id.profileUuid").is(profileUuid); + Query query = Query.query(criteria); + this.mongoTemplate.remove(query, DeviceProfileState.class); + } + + public void resetDevice(UUID deviceUuid) { + this.deleteByDeviceUuid(deviceUuid); + Criteria criteria = Criteria.where("_id.deviceUuid").is(deviceUuid); + Query query = Query.query(criteria); + this.mongoTemplate.remove(query, DeviceProfileState.class); + } + + public void deleteByDeviceUuid(UUID deviceUuid) { + Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid); + Query query = Query.query(criteria); + BulkOperations bulkOp = this.mongoTemplate.bulkOps(BulkMode.UNORDERED, DeviceReport.class); + bulkOp.remove(query); + bulkOp.execute(); + } + + private Query stateQuery(UUID deviceUuid, DeviceProfile profile) { + long updated = profile.getUpdated().getTime(); + Criteria criteria = Criteria.where("_id.profileUuid").is(profile.getUuid()).and("_id.deviceUuid").is(deviceUuid).orOperator(new Criteria[]{Criteria.where("updated").is(updated), Criteria.where("updated").is(updated - 1L)}); + return Query.query(criteria); + } + + private String propertyName(String item) { + return this.propertyName(item, (String)null); + } + + private String propertyName(String item, String key) { + return Joiner.on('.').skipNulls().join("properties", item, new Object[]{key}); + } + + private Date secondsLater(int seconds) { + return DateTime.now().plusSeconds(seconds).toDate(); + } + + private void requestCallbackApi(UUID siteUuid, Collection reports) { + if (reports != null && !reports.isEmpty()) { + Iterator it = reports.iterator(); + + while(it.hasNext()) { + DeviceReport report = (DeviceReport)it.next(); + DbObject properties = report.getProperties(); + if (properties.containsKey("deviceProfile")) { + properties.remove("deviceProfile"); + if (properties.isEmpty()) { + it.remove(); + } + } + } + + ExternalApiService.doRequestCallback(this.siteService.findByUuid(siteUuid), reports); + } + } + + private void requestCallbackApi(UUID siteUuid, DeviceReport report) { + if (report != null) { + ExternalApiService.doRequestCallback(this.siteService.findByUuid(siteUuid), Arrays.asList(report)); + } + } +} diff --git a/src/main/java/com/midm/service/device/DeviceService.java b/src/main/java/com/midm/service/device/DeviceService.java new file mode 100644 index 0000000..d91cabc --- /dev/null +++ b/src/main/java/com/midm/service/device/DeviceService.java @@ -0,0 +1,2397 @@ +package com.midm.service.device; + +import com.google.common.base.CharMatcher; +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.GeneralProfile; +import com.midm.model.GroupByResult; +import com.midm.model.device.AppInfo; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceApps; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceLicense; +import com.midm.model.device.DeviceNote; +import com.midm.model.device.DeviceProfile; +import com.midm.model.log.MidmLog; +import com.midm.model.org.Site; +import com.midm.model.org.SiteLicense; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.repository.device.DeviceLicenseRepository; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.ScheduledTaskService; +import com.midm.service.battery.BatteryService; +import com.midm.service.log.LogService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.LicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.barcode.QrCode; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.security.McBase64; +import com.mitac.cell.security.McTextEncryptor; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.DBRef; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import java.awt.image.BufferedImage; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.compress.utils.Sets; +import org.bson.Document; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.aggregation.LookupOperation; +import org.springframework.data.mongodb.core.aggregation.MatchOperation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.socket.CloseStatus; +import org.thymeleaf.context.Context; + +/** + * ====================================================================================== + * 核心设备领域服务与生命周期管控中心 (DeviceService) + * ====================================================================================== + * + *

【业务中枢与核心职责】 + * 1. 终端接入与全生命周期管理: + * - 设备入网注册绑定(Enrollment):校验硬件序列号(SN)、激活商业授权 License、 + * 自动分配企业租户(Site)与层级部门分组(DeviceGroup); + * - 快速开箱入网:支持基于 AES 加密二维码扫描(QR Code Enrollment)的零接触配置(Zero-Touch); + * - 设备全状态维护:在线心跳监测、离线判定定时任务、设备安全锁机与远程数据擦除(Remote Wipe)。 + * 2. 【多租户与层级分组拓扑】: + * - 维护多级树状分组路径(如 `华南大区/智能物流园/冷链车队`),支持策略按分组继承下发。 + * 3. 固件与系统升级回调处理: + * - 处理 OTA 固件更新事件(`systemImageUpdated` / `regionImageUpdated`),记录升级审计日志。 + * 4. 商业授权计算与配额管理: + * - 严格管控各租户的有效设备激活数量,过期自动断开长连接。 + * + * @author MiDM Core Platform Team + */ +@Service +@EnableScheduling +public class DeviceService extends BaseService { + @Autowired + @Lazy + private UserService userService; + @Autowired + @Lazy + private SettingsService settingsService; + @Autowired + @Lazy + private SiteService siteService; + @Autowired + @Lazy + private ProfileService profileService; + @Autowired + @Lazy + private BatteryService batteryService; + @Autowired + @Lazy + private WebSocketSessionManager sessionManager; + @Autowired + @Lazy + private ScheduledTaskService scheduledTaskService; + @Autowired + @Lazy + private HostLicenseService hostLicenseService; + @Autowired + private LicenseService licenseService; + @Autowired + private DeviceLicenseRepository deviceLicenseRepository; + @Autowired + @Lazy + private DeviceReportService deviceReportService; + @Autowired + @Lazy + private DeviceAppsService deviceAppsService; + @Autowired + @Lazy + private DeviceKeyService deviceKeyService; + @Autowired + @Lazy + private EmailService emailService; + @Autowired + private LogService logService; + private static Set sitesBlockAllowed = new HashSet(); + private static final Set roamingProblemClientVersions = new HashSet(Arrays.asList(240L, 241L, 1085L)); + + public Device save(Device device) { + return this.save(device, true); + } + + public Device save(Device device, boolean notify) { + if (device != null && device.canRegister()) { + if (!device.getEnabled()) { + this.sessionManager.close(device.getUuid(), CloseStatus.NOT_ACCEPTABLE); + } + + Device existingDevice = this.findBySerialNo(device.getSerialNo()); + if (existingDevice == null && this.isExceedDeviceLimit()) { + return null; + } else { + UUID curGroupUuid = existingDevice == null ? null : (existingDevice.getDeviceGroup() == null ? null : existingDevice.getDeviceGroup().getUuid()); + UUID newGroupUuid = device.getDeviceGroup() == null ? null : device.getDeviceGroup().getUuid(); + if (curGroupUuid == null && newGroupUuid != null || curGroupUuid != null && !curGroupUuid.equals(newGroupUuid)) { + this.scheduleToUpdateProfile(device, 5); + } + + if (existingDevice == null && !this.hostLicenseService.isStandalone() && device.getLicense() == null) { + DeviceLicense license = this.setTrialLicense(device); + device.setLicense(license); + } + + if (device.getOwner() == null) { + Object email = device.getCategoryProfile("owner", "email"); + if (email != null) { + User owner = this.userService.findUserByEmail(device.getSiteUuid(), (String)email); + if (owner != null && owner.isBelongedToSite(device.getSiteUuid())) { + device.setOwner(owner); + device.removeProfile("owner"); + } + } + } + + Device savedDevice = (Device)this.saveDocument(device); + if (!Strings.isNullOrEmpty(savedDevice.getRsa())) { + this.deviceKeyService.save(savedDevice.getSerialNo(), savedDevice.getRsa()); + } + + if (notify) { + if (existingDevice == null) { + this.sessionManager.sendMessageToOnlineUsers((Device)device, 113); + } else { + this.sessionManager.sendMessageToOnlineUsers((Device)device, 114); + } + } + + if (!this.hostLicenseService.isStandalone() && savedDevice.isLicenseExpired()) { + this.sessionManager.close(savedDevice.getUuid(), CloseStatus.NOT_ACCEPTABLE); + } + + return savedDevice; + } + } else { + return null; + } + } + + public void scheduleToUpdateProfile(Device device, int minLater) { + this.scheduledTaskService.scheduleToUpdateProfile(device, minLater); + } + + public List saveDevices(List devices) { + List savedDevices = new ArrayList(); + + for(Device device : devices) { + Device savedDevice = this.save(device, false); + savedDevices.add(savedDevice); + } + + if (!savedDevices.isEmpty()) { + this.sessionManager.sendMessageToOnlineUsers((List)devices, 113); + } + + return savedDevices; + } + + public Device register(HttpServletRequest request, HttpServletResponse response, Device device) { + if (this.isExceedDeviceLimit()) { + return null; + } else { + device.init(); + User owner = null; + if (device.getOwnerUuid() != null) { + owner = (User)this.findById(User.class, device.getOwnerUuid()); + if (owner == null) { + Object email = device.getProfile("owner", "email"); + if (email != null) { + owner = this.userService.findUserByEmail(device.getSiteUuid(), (String)email); + } + } + } + + if (owner != null && owner.isBelongedToSite(device.getSiteUuid())) { + device.setOwner(owner); + device.removeProfile("owner"); + } else { + device.setOwner((User)null); + } + + if (device.getGroupUuid() != null) { + DeviceGroup group = this.findDeviceGroup(device.getGroupUuid()); + device.setDeviceGroup(group); + } + + if (!this.hostLicenseService.isStandalone()) { + DeviceLicense license = this.setTrialLicense(device); + device.setLicense(license); + } + + return this.save(device); + } + } + + public DeviceLicense setTrialLicense(Device device) { + if (this.hostLicenseService.isStandalone()) { + return null; + } else { + List licenses = this.getLicenses(device); + Site site = this.siteService.findByUuid(device.getSiteUuid()); + LicenseModel trialLicenseModel = this.licenseService.getTrialLicenseModel(); + DeviceLicense trialLicense = null; + if (!licenses.isEmpty()) { + for(DeviceLicense license : licenses) { + LicenseModel licenseModel = license.getLicenseModel(); + if (licenseModel == null) { + licenseModel = trialLicenseModel; + license.setLicenseModel(trialLicenseModel, false); + } + + if (licenseModel == null || !licenseModel.getIdName().equals("smb")) { + if (license.isTrial()) { + license.setPlan(site.getPlanName()); + trialLicense = license; + license.setDevice(device); + this.save(license); + } else { + this.resetLicense(license); + } + } + } + + if (trialLicense != null) { + return trialLicense; + } + } + + trialLicense = new DeviceLicense(device, trialLicenseModel); + trialLicense.setPlan(site.getPlanName()); + trialLicense = this.setTrialLicenseSite(trialLicense, site); + return this.save(trialLicense); + } + } + + public DeviceLicense setTrialLicenseSite(DeviceLicense trialLicense, Site site) { + if (site.isChild()) { + trialLicense.setSite(site.getReseller()); + trialLicense.setChildSite(site); + } else { + trialLicense.setSite(site); + trialLicense.setChildSite((Site)null); + } + + return trialLicense; + } + + public int getDeviceLimit() { + return this.hostLicenseService.getDeviceLimit(); + } + + public boolean isExceedDeviceLimit() { + return this.hostLicenseService.isExceedDeviceLimit(); + } + + public Device findDeviceByUuid(UUID uuid) { + if (uuid == null) { + return null; + } else { + Device device = (Device)this.findById(Device.class, uuid); + if (device == null) { + return null; + } else { + if (device.hasOwner()) { + device.getOwner().setProfileOnly(); + } + + if (!device.hasLicense() && !this.hostLicenseService.isStandalone()) { + DeviceLicense license = this.getTrialLicense(device); + license.setDevice(device); + this.save(license); + device.setLicense(license); + device = (Device)this.saveDocument(device); + } + + return device; + } + } + } + + public UUID getSiteUuid(UUID deviceUuid) { + if (deviceUuid == null) { + return null; + } else { + Query query = Query.query(Criteria.where("_id").is(deviceUuid)); + query.fields().include("siteUuid"); + Device device = (Device)this.mongoTemplate.findOne(query, Device.class); + return device != null ? device.getSiteUuid() : null; + } + } + + public UUID getSiteUuid(String serialNo) { + if (Strings.isNullOrEmpty(serialNo)) { + return null; + } else { + Query query = Query.query(Criteria.where("profile.hardware_info.serial_no").is(serialNo)); + query.fields().include("siteUuid"); + Device device = (Device)this.mongoTemplate.findOne(query, Device.class); + return device != null ? device.getSiteUuid() : null; + } + } + + public Device findOnlineDeviceFirst(UUID deviceUuid) { + Device device = this.sessionManager.getOnlineDevice(deviceUuid); + return device != null ? device : (Device)this.findById(Device.class, deviceUuid); + } + + public List findDevicesBySiteUuid(UUID siteUuid) { + return this.mongoTemplate.find(Query.query(Criteria.where("siteUuid").is(siteUuid)), Device.class); + } + + public List findDevicesOrderByExpiry(UUID siteUuid, boolean includedDisabled, int limit) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("states.state").ne("retired"); + if (!includedDisabled) { + criteria.and("enabled").is(true); + } + + Query query = Query.query(criteria).with(Sort.by(Direction.ASC, new String[]{"licenseExpiry"})).limit(limit); + return this.mongoTemplate.find(query, Device.class); + } + + public List findDevicesToApplyLicense(UUID siteUuid, boolean includedDisabled) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("states.state").ne("retired"); + if (!includedDisabled) { + criteria.and("enabled").is(true); + } + + Query query = Query.query(criteria).with(Sort.by(Direction.ASC, new String[]{"updated"})); + return this.mongoTemplate.find(query, Device.class); + } + + public List findDevicesByUser(UUID userUuid) { + return this.mongoTemplate.find(Query.query(Criteria.where("owner.$id").is(userUuid)), Device.class); + } + + public UpdateResult removeOwner(UUID userUuid) { + return this.mongoTemplate.updateMulti(Query.query(Criteria.where("owner.$id").is(userUuid)), (new Update()).unset("owner"), Device.class); + } + + public Device findBySerialNo(String serialNo) { + if (Strings.isNullOrEmpty(serialNo)) { + return null; + } else { + Criteria criteria = Criteria.where("profile.hardware_info.serial_no").is(serialNo); + Query query = new Query(criteria); + Device device = (Device)this.mongoTemplate.findOne(query, Device.class); + return device; + } + } + + public Device findBySerialNo(UUID siteUuid, String serialNo) { + if (Strings.isNullOrEmpty(serialNo)) { + return null; + } else { + Criteria criteria; + if (siteUuid != null) { + criteria = Criteria.where("siteUuid").is(siteUuid).and("profile.hardware_info.serial_no").regex(McMongoUtils.escapedPattern(serialNo)); + } else { + criteria = Criteria.where("profile.hardware_info.serial_no").is(serialNo); + } + + Query query = new Query(criteria); + return (Device)this.mongoTemplate.findOne(query, Device.class); + } + } + + public UUID getDeviceUuid(String serialNo) { + if (Strings.isNullOrEmpty(serialNo)) { + return null; + } else { + Criteria criteria = Criteria.where("profile.hardware_info.serial_no").is(serialNo); + Query query = new Query(criteria); + query.fields().include("_id"); + Device device = (Device)this.mongoTemplate.findOne(query, Device.class); + return device != null ? device.getUuid() : null; + } + } + + public String getDeviceSerial(UUID deviceUuid) { + if (deviceUuid == null) { + return null; + } else { + Criteria criteria = Criteria.where("_id").is(deviceUuid); + Query query = new Query(criteria); + query.fields().include("profile.hardware_info.serial_no"); + Device device = (Device)this.mongoTemplate.findOne(query, Device.class); + return device != null ? device.getSerialNo() : null; + } + } + + public Device findLastestVisit(UUID siteUuid) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid); + Sort sort = Sort.by(Direction.DESC, new String[]{"updated"}); + return (Device)this.mongoTemplate.findOne(Query.query(criteria).with(sort), Device.class); + } + + public boolean exists(Device device) { + if (device != null) { + boolean exists = this.existsById(Device.class, device.getUuid()); + return exists; + } else { + return false; + } + } + + public boolean exists(UUID siteUuid, String serialNo) { + Criteria criteria = Criteria.where("profile.hardware_info.serial_no").is(serialNo); + if (siteUuid != null) { + criteria.and("siteUuid").is(siteUuid); + } + + return this.mongoTemplate.exists(Query.query(criteria), Device.class); + } + + public Page findDevices(UUID siteUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction, boolean blocked, Integer expiry) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.hardware_info.serial_no"; + direction = Direction.ASC; + } + + List criterias = new ArrayList(); + criterias.add(Criteria.where("siteUuid").is(siteUuid)); + if (filter != null) { + for(Map.Entry entry : filter.entrySet()) { + String key = (String)entry.getKey(); + JsonElement value = (JsonElement)entry.getValue(); + switch (key) { + case "siteUuid": + break; + case "owner.uuid": + criterias.add(Criteria.where("owner.$id").is(UUID.fromString(value.getAsString()))); + break; + case "states.batteryCondition": + int batteryCondition = value.getAsInt(); + if (batteryCondition >= 0 && batteryCondition <= 2) { + criterias.add(Criteria.where(key).is(batteryCondition)); + break; + } + + criterias.add(Criteria.where(key).nin(new Object[]{0, 1, 2})); + break; + case "deviceGroups": + JsonArray jGroups = value.getAsJsonArray(); + List groupsCriteria = new ArrayList(); + if (!jGroups.isEmpty()) { + for(JsonElement jGroup : jGroups) { + UUID groupUuid = UUID.fromString(jGroup.getAsString()); + List groups = this.findGroupFamily(groupUuid); + groups.forEach((group) -> groupsCriteria.add(Criteria.where("deviceGroup.$id").is(group.getUuid()))); + } + + if (!groupsCriteria.isEmpty()) { + criterias.add((new Criteria()).orOperator(groupsCriteria)); + } + break; + } + + criterias.add(Criteria.where("deviceGroup").exists(false)); + break; + default: + criterias.add(Criteria.where(key).regex(McMongoUtils.escapedPattern(value.getAsString()))); + } + } + } + + if (expiry != null) { + Date now = new Date(); + if (expiry == -1) { + criterias.add(Criteria.where("licenseExpiry").lt(now)); + } else if (expiry == 0) { + criterias.add((new Criteria()).orOperator(new Criteria[]{Criteria.where("licenseExpiry").gte(now), Criteria.where("licenseExpiry").exists(false)})); + } else { + criterias.add((new Criteria()).andOperator(new Criteria[]{Criteria.where("licenseExpiry").lt((new DateTime()).plusDays(expiry).toDate()), Criteria.where("licenseExpiry").gte(now)})); + } + } + + if (blocked) { + criterias.add((new Criteria("states.blocked")).exists(true)); + } + + Query query = Query.query((new Criteria()).andOperator(criterias)); + Sort sort = Sort.by(direction, new String[]{sortBy}); + if (!sortBy.equals("profile.hardware_info.serial_no")) { + sort = sort.and(Sort.by(direction, new String[]{"profile.hardware_info.serial_no"})); + } + + query.with(sort); + if (filter != null && filter.has("owner.uuid")) { + query.fields().exclude("owner"); + } + + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, Device.class); + if (total > 0L) { + page = this.page(total, page, size); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), Device.class); + + for(Device device : result) { + device.setOnline(this.sessionManager.isOnline(device.getUuid())); + if (!this.hostLicenseService.isStandalone() && !device.hasLicense()) { + device.setLicense(this.setTrialLicense(device)); + this.save(device); + } + + if (device.isOnline()) { + this.sessionManager.ping(device.getUuid()); + } + + if (device.hasOwner()) { + device.getOwner().setProfileOnly(); + } + } + + return new PageImpl(result, pageable, total); + } else { + Pageable pageable = PageRequest.of(0, size); + return new PageImpl(new ArrayList(), pageable, total); + } + } + + public List findDevices(JsonObject filter, String sortBy, Sort.Direction direction, Integer expiry) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.hardware_info.serial_no"; + direction = Direction.ASC; + } + + Query query = new Query(); + Criteria criteriaFilter = McMongoUtils.toCriteria(filter); + if (expiry != null) { + Criteria criteria = new Criteria(); + Date now = new Date(); + if (expiry == -1) { + criteria.and("licenseExpiry").lt(now); + } else if (expiry == 0) { + criteria.orOperator(new Criteria[]{Criteria.where("licenseExpiry").gte(now), Criteria.where("licenseExpiry").exists(false)}); + } else { + criteria.andOperator(new Criteria[]{Criteria.where("licenseExpiry").lt((new DateTime()).plusDays(expiry).toDate()), Criteria.where("licenseExpiry").gte(now)}); + } + + query.addCriteria((new Criteria()).andOperator(new Criteria[]{criteriaFilter, criteria})); + } else { + query.addCriteria(criteriaFilter); + } + + Sort sort = Sort.by(direction, new String[]{sortBy}); + query.with(sort); + this.mongoTemplate.count(query, Device.class); + List result = this.mongoTemplate.find(query, Device.class); + return result; + } + + public List findDevices(UUID siteUuid, String... devices) { + if (devices.length == 0) { + return null; + } else { + List uuids = new ArrayList(); + List serials = new ArrayList(); + + for(String device : devices) { + try { + if (device.length() == 36) { + uuids.add(UUID.fromString(device)); + } else { + serials.add(device); + } + } catch (Exception var10) { + serials.add(device); + } + } + + List criterias = new ArrayList(); + if (!uuids.isEmpty()) { + criterias.add(Criteria.where("_id").in(uuids)); + } + + if (!serials.isEmpty()) { + criterias.add(Criteria.where("profile.hardware_info.serial_no").in(serials)); + } + + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).orOperator(criterias)); + return this.mongoTemplate.find(query, Device.class); + } + } + + public List findDeviceByGroupUuid(UUID groupUuid) { + return this.mongoTemplate.find(Query.query(Criteria.where("deviceGroup.$id").is(groupUuid)), Device.class); + } + + public List findDeviceByGroupUuids(UUID siteUuid, List groupUuids, String... fieldsToInclude) { + if (groupUuids != null && !groupUuids.isEmpty()) { + List groups = new ArrayList(); + groupUuids.forEach((uuid) -> groups.addAll(this.findGroupFamily(uuid))); + Criteria criteria = new Criteria(); + if (siteUuid != null) { + criteria.and("siteUuid").is(siteUuid); + } + + if (groupUuids != null) { + if (groupUuids.isEmpty()) { + criteria.and("deviceGroup").exists(false); + } else { + List criterias = new ArrayList(); + groups.forEach((group) -> criterias.add(Criteria.where("deviceGroup.$id").is(group.getUuid()))); + criteria.orOperator(criterias); + } + } + + Query query = new Query(criteria); + if (fieldsToInclude.length > 0) { + query.fields().include(fieldsToInclude); + } + + return this.mongoTemplate.find(query, Device.class); + } else { + return null; + } + } + + public List findGroupFamily(UUID groupUuid) { + List groups = new ArrayList(); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("_id").is(groupUuid)), Aggregation.graphLookup("deviceGroup").startWith(new String[]{"$_id"}).connectFrom("_id").connectTo("parentUuid").as("children")}); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceGroup.class, DeviceGroup.class); + List foundGroups = results.getMappedResults(); + if (!foundGroups.isEmpty()) { + DeviceGroup group = (DeviceGroup)foundGroups.get(0); + List children = group.getChildren(); + if (children != null) { + group.setChildren((List)null); + groups.add(group); + groups.addAll(children); + } + } + + return groups; + } + + public List findGroupUUids(Collection groupUuids) { + List groups = new ArrayList(); + groupUuids.forEach((uuid) -> groups.addAll(this.findGroupFamily(uuid))); + return (List)groups.stream().map((groupElement) -> groupElement.getUuid()).collect(Collectors.toList()); + } + + public List findChildGroups(UUID parentGroupUuid) { + Query query = Query.query(Criteria.where("parentUuid").is(parentGroupUuid)); + return this.mongoTemplate.find(query, DeviceGroup.class); + } + + public List findAllDevicesInGroup(UUID groupUuid, JsonObject jFilter) { + String sortBy = "profile.hardware_info.serial_no"; + Sort.Direction direction = Direction.ASC; + if (jFilter == null) { + jFilter = new JsonObject(); + } + + jFilter.addProperty("deviceGroup.uuid", groupUuid.toString()); + List devices = this.find(Device.class, jFilter, sortBy, direction); + + for(DeviceGroup childGroup : this.findChildGroups(groupUuid)) { + devices.addAll(this.findAllDevicesInGroup(childGroup.getUuid(), jFilter)); + } + + return devices; + } + + public List findAllDevices() { + return this.findAll(Device.class); + } + + public boolean isInDeviceGroup(Device device, UUID groupUuid) { + if (device != null && device.getGroupUuid() != null) { + if (device.getGroupUuid().equals(groupUuid)) { + return true; + } else { + for(DeviceGroup group : this.findChildGroups(groupUuid)) { + if (this.isInDeviceGroup(device, group.getUuid())) { + return true; + } + } + + return false; + } + } else { + return false; + } + } + + public int delete(UUID siteUuid, List deviceUuids) { + if (siteUuid != null && deviceUuids != null && !deviceUuids.isEmpty()) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("_id").in(deviceUuids); + Query query = Query.query(criteria); + List devices = this.mongoTemplate.find(query, Device.class); + int deletedCount = 0; + + for(Device device : devices) { + if (this.delete(device, false)) { + ++deletedCount; + } + } + + return deletedCount; + } else { + return 0; + } + } + + public void deleteBySite(UUID siteUuid) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid); + Query query = Query.query(criteria); + List devices = this.mongoTemplate.find(query, Device.class); + devices.forEach((device) -> this.delete(device, false)); + this.mongoTemplate.remove(query, DeviceGroup.class); + } + + public void deleteNotesByDevice(UUID deviceUuid) { + Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); + this.mongoTemplate.remove(query, DeviceNote.class); + } + + public boolean delete(Device device, boolean forceToRemove) { + if (device != null && device.getUuid() != null) { + if (!forceToRemove) { + DeviceLicense license = device.getLicense(); + if (license != null) { + if (license.isTrial()) { + if (license.beforeExpiry()) { + license.expire(); + } + } else if (license.isExceedActivationCount() && license.beforeExpiry()) { + if (!device.isRetired()) { + return false; + } + + license.expire(); + } else { + license.reset(); + } + + this.save(license); + } + } + + UUID deviceUuid = device.getUuid(); + this.deleteById(Device.class, deviceUuid); + this.deleteNotesByDevice(deviceUuid); + this.resetDevice(device, true); + this.sessionManager.close(deviceUuid, CloseStatus.NOT_ACCEPTABLE); + return true; + } else { + return false; + } + } + + public DeleteResult deleteDeviceGroupBySiteUuid(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.remove(query, DeviceGroup.class); + } + + public List findAllDeviceGroupBySiteUuid(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.find(query, DeviceGroup.class); + } + + public DeleteResult deleteDeviceLicenseBySiteLicense(SiteLicense siteLicense) { + Query query = Query.query(Criteria.where("siteLicense.$id").is(siteLicense.getUuid())); + return this.mongoTemplate.remove(query, DeviceLicense.class); + } + + public UpdateResult retire(UUID siteUuid, List deviceUuids) { + if (siteUuid != null && deviceUuids != null && !deviceUuids.isEmpty()) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("_id").in(deviceUuids).and("states.state").ne("retired"); + Query query = Query.query(criteria); + List devices = this.mongoTemplate.find(query, Device.class); + if (devices.isEmpty()) { + return null; + } else { + devices.forEach((device) -> this.retireDeviceLicense(device)); + Update update = Update.update("enabled", false).set("states.state", "retired").unset("deviceGroup").unset("owner").unset("profile.owner"); + UpdateResult updateResult = this.mongoTemplate.updateMulti(query, update, Device.class); + devices.forEach((device) -> this.sessionManager.close(device.getUuid(), CloseStatus.NOT_ACCEPTABLE)); + return updateResult; + } + } else { + return null; + } + } + + public void retireDeviceLicense(Device device) { + DeviceLicense license = this.getTrialLicense(device); + if (license != null && !license.isExpired()) { + license.expire(); + this.save(license); + } + + license = device.getLicense(); + if (license != null && !license.isExpired() && license.isExceedActivationCount()) { + license.expire(); + this.save(license); + } + + device.setLicense((DeviceLicense)null); + this.save(device); + } + + public long updateDeviceGroup(Device device, DeviceGroup group) { + if (device != null && group != null) { + if (!device.getSiteUuid().equals(group.getSiteUuid())) { + return 0L; + } else { + Criteria criteria = Criteria.where("_id").is(device.getUuid()); + Query query = Query.query(criteria); + Update update = Update.update("groupUuid", group.getUuid()).set("updated", new Date()); + return this.mongoTemplate.updateMulti(query, update, Device.class).getModifiedCount(); + } + } else { + return 0L; + } + } + + public long unsetDeviceGroup(Device device) { + if (device != null && device.getDeviceGroup() != null) { + Criteria criteria = Criteria.where("_id").is(device.getUuid()); + Query query = Query.query(criteria); + Update update = Update.update("updated", new Date()).unset("deviceUuid"); + return this.mongoTemplate.updateFirst(query, update, Device.class).getModifiedCount(); + } else { + return 0L; + } + } + + public long updateDeviceGroup(List devices, DeviceGroup group) { + if (devices != null && !devices.isEmpty()) { + List criterias = new ArrayList(); + + for(Device device : devices) { + criterias.add(Criteria.where("_id").is(device.getUuid())); + } + + if (criterias.isEmpty()) { + return 0L; + } else { + Query query = Query.query((new Criteria()).orOperator((Criteria[])criterias.toArray(new Criteria[criterias.size()]))); + Update update = Update.update("updated", new Date()); + if (group != null) { + update.set("deviceGroup", (new DbObject("$ref", "deviceGroup")).append("$id", group.getUuid())); + } else { + update.unset("deviceGroup"); + } + + long changed = this.mongoTemplate.updateMulti(query, update, Device.class).getModifiedCount(); + if (changed > 0L) { + for(Device device : devices) { + this.profileService.notifyUpdate(device); + } + } + + return changed; + } + } else { + return 0L; + } + } + + public long updateDeviceOwner(UUID siteUuid, User user, boolean registered) { + if (siteUuid == null) { + return 0L; + } else { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("owner.$id").is(user.getUuid()); + if (registered) { + criteria.and("profile.owner.email").is(user.getEmail()); + } + + Update update = registered ? Update.update("owner", new DBRef("user", user.getUuid())) : (new Update()).unset("owner"); + update.unset("profile.owner"); + UpdateResult result = this.mongoTemplate.updateMulti(Query.query(criteria), update, Device.class); + return result.getModifiedCount(); + } + } + + public long updateDeviceOwner(List devices, User owner) { + if (devices != null && !devices.isEmpty()) { + List criterias = new ArrayList(); + + for(Device device : devices) { + criterias.add(Criteria.where("_id").is(device.getUuid())); + } + + if (criterias.isEmpty()) { + return 0L; + } else { + Query query = Query.query((new Criteria()).orOperator((Criteria[])criterias.toArray(new Criteria[criterias.size()]))); + Update update = Update.update("updated", new Date()); + if (owner != null) { + if (owner.getUuid() != null) { + update.unset("profile.owner").set("owner", (new Document("$ref", "user")).append("$id", owner.getUuid())); + } else { + Document ownerDoc = new Document("email", owner.getEmail()); + ownerDoc.putAll(owner.getProfile()); + update.unset("owner").set("profile.owner", ownerDoc); + } + } else { + update.unset("owner").unset("profile.owner"); + } + + long changed = this.mongoTemplate.updateMulti(query, update, Device.class).getModifiedCount(); + if (changed > 0L) { + for(Device device : devices) { + this.profileService.notifyUpdate(device); + } + } + + return changed; + } + } else { + return 0L; + } + } + + public UpdateResult updateProfile(UUID deviceUuid, String key, Object value) { + Query query = new Query(Criteria.where("_id").is(deviceUuid)); + Update update = Update.update("profile." + key, value).set("updated", new Date()); + return this.mongoTemplate.updateFirst(query, update, Device.class); + } + + public UpdateResult updateDeviceInfo(Device device, Document profile) { + Query query = new Query(Criteria.where("_id").is(device.getUuid())); + Update update = Update.update("updated", new Date()); + DbObject dbProfile = new DbObject(profile); + if (dbProfile.containsKey("hardware_info") && !dbProfile.getDbObject(new String[]{"hardware_info"}).containsKey("sku_id")) { + device.setProfile(new DbObject(profile)); + String skuId = device.getSkuId(); + dbProfile.getDbObject(new String[]{"hardware_info"}).put("sku_id", skuId); + } + + dbProfile.forEach((key, value) -> { + update.set("profile." + key, value); + if (key.equals("hardware_info")) { + DbObject batteryObj = (new DbObject((Map)value)).getDbObject(new String[]{"battery"}); + this.batteryService.updateBatteryFromInstant(device, batteryObj); + } + + }); + UpdateResult result = this.mongoTemplate.updateFirst(query, update, Device.class); + this.sessionManager.sendMessageToOnlineUsers((Device)device, 114); + return result; + } + + public UpdateResult updateDeviceStatus(UUID deviceUuid, Document states) { + Query query = new Query(Criteria.where("_id").is(deviceUuid)); + Update update = new Update(); + states.forEach((key, value) -> { + String actualKey = "states." + key; + if (value != null) { + update.set(actualKey, value); + } else { + update.unset(actualKey); + } + + }); + return this.mongoTemplate.updateFirst(query, update, Device.class); + } + + public UpdateResult updateOnlineStatus(UUID deviceUuid, boolean isOnline) { + String key = "states.isOnline"; + Query query = new Query(Criteria.where("_id").is(deviceUuid).and("states.isOnline").ne(isOnline)); + Update update = new Update(); + if (isOnline) { + update.set("states.isOnline", isOnline); + } else { + update.set("lastDisconnected", new Date()).unset("states.isOnline"); + } + + return this.mongoTemplate.updateFirst(query, update, Device.class); + } + + public UpdateResult updateActiveNetwork(UUID deviceUuid, String ipAddress, Map data) { + if (data != null) { + if (!Strings.isNullOrEmpty(ipAddress)) { + data.put("public_ip", ipAddress); + } + + return data.containsKey("type") && data.get("type").equals("wifi") ? this.update(deviceUuid, "profile.network.active", data, "profile.network.wifi", data) : this.update(deviceUuid, "profile.network.active", data); + } else { + return null; + } + } + + public UpdateResult updatePublicIp(UUID deviceUuid, String ipAddress) { + return !Strings.isNullOrEmpty(ipAddress) ? this.update(deviceUuid, "profile.network.active.public_ip", ipAddress) : null; + } + + public UpdateResult updateTelephony(UUID deviceUuid, DbObject data) { + return data != null ? this.update(deviceUuid, "profile.network.telephony", data) : null; + } + + public UpdateResult updateCameraStatus(UUID deviceUuid, String status) { + String key = "states.camera"; + Query query = new Query(Criteria.where("_id").is(deviceUuid)); + Update update = new Update(); + update.set("states.camera", status); + return this.mongoTemplate.updateFirst(query, update, Device.class); + } + + public UpdateResult updateLastCheckedIn(UUID deviceUuid) { + Query query = new Query(Criteria.where("_id").is(deviceUuid)); + Date date = new Date(); + Update update = (new Update()).set("lastCheckedIn", date); + return this.mongoTemplate.updateFirst(query, update, Device.class); + } + + public Device validateLicense(Device device) { + if (device != null && device.getEnabled()) { + if (!this.hostLicenseService.isStandalone()) { + DeviceLicense license = device.getLicense(); + if (license != null) { + if (!license.isPerpetual() && device.isLicenseExpired() && license.isAutoRenew()) { + return this.renewLicense(device) ? device : null; + } else { + return device; + } + } else { + return null; + } + } else { + return !this.hostLicenseService.isValid() && !this.hostLicenseService.isExceedDeviceLimit() ? device : null; + } + } else { + return null; + } + } + + public UpdateResult updateDeviceTimeZone(UUID deviceUuid, String timeZone) { + Query query = new Query(Criteria.where("_id").is(deviceUuid)); + String key = "states.timeZone"; + Update update = !Strings.isNullOrEmpty(timeZone) ? Update.update("states.timeZone", timeZone) : (new Update()).unset("states.timeZone"); + return this.mongoTemplate.updateFirst(query, update, Device.class); + } + + public UpdateResult updateBlockState(UUID deviceUuid, Date from, Date to) { + Query query = new Query(Criteria.where("_id").is(deviceUuid)); + String key = "states.blocked"; + Update update = from != null ? Update.update("states.blocked", (new Document("from", from)).append("to", to)) : (new Update()).unset("states.blocked"); + return this.mongoTemplate.updateFirst(query, update, Device.class); + } + + public UpdateResult update(UUID deviceUuid, Object... keyValue) { + if (deviceUuid != null && keyValue != null && keyValue.length != 0 && keyValue.length % 2 <= 0) { + Query query = new Query(Criteria.where("_id").is(deviceUuid)); + Update update = Update.update("updated", new Date()); + + for(int i = 0; i < keyValue.length; ++i) { + if (keyValue[i] instanceof String) { + String key = (String)keyValue[i]; + ++i; + Object value = keyValue[i]; + if (value != null) { + update.set(key, value); + } else { + update.unset(key); + } + } + } + + return this.mongoTemplate.updateFirst(query, update, Device.class); + } else { + return null; + } + } + + public void systemImageUpdated(Device device, boolean isSameSku, String prevDisplayId, String curDisplayId, long prevBuildDate, long curBuildDate) { + boolean isUpgraded = false; + String state; + if (isSameSku) { + isUpgraded = prevBuildDate < curBuildDate; + state = isUpgraded ? "upgraded" : "downgraded"; + } else { + state = "replaced"; + } + + String log = String.format("System image has been %s to %s from %s.", state, curDisplayId, prevDisplayId); + this.logService.saveDeviceLog(device.getUuid(), "activity", log, new Date()); + this.updateProfileState(device); + } + + public void regionImageUpdated(Device device, String prevRegionVersion, String curRegionVersion, String prevScriptVersion, String curScriptVersion) { + String curVersion = Strings.isNullOrEmpty(curRegionVersion) ? "" : String.format("%s(%s)", curRegionVersion, curScriptVersion); + String prevVersion = Strings.isNullOrEmpty(prevRegionVersion) ? "" : String.format("%s(%s)", prevRegionVersion, prevScriptVersion); + String log = String.format("Region image has been updated to %s from %s.", curVersion, prevVersion); + this.logService.saveDeviceLog(device.getUuid(), "activity", log, new Date()); + this.updateProfileState(device); + } + + private void updateProfileState(Device device) { + List profiles = this.profileService.findAllByDevice(device, false, true, false); + if (profiles != null && !profiles.isEmpty()) { + profiles.forEach((profile) -> { + List otas = profile.getOtas(); + if (otas != null && !otas.isEmpty()) { + this.deviceReportService.updateDeviceProfileState(device, profile); + } + + }); + } + } + + public boolean blockAllowed(UUID siteUuid) { + return sitesBlockAllowed != null && sitesBlockAllowed.contains(siteUuid); + } + + public void setBlockAllowed(UUID siteUuid, boolean allowed) { + if (allowed) { + sitesBlockAllowed.add(siteUuid); + } else { + sitesBlockAllowed.remove(siteUuid); + this.sessionManager.unblockBySiteUuid(siteUuid); + } + + } + + public void initDeviceStatus() { + Query query = Query.query(Criteria.where("settings.device.blockAllowed").is(true)); + query.fields().include("_id"); + List blockedSites = this.mongoTemplate.find(query, Site.class); + blockedSites.forEach((site) -> sitesBlockAllowed.add(site.getUuid())); + Date min5Later = DateTime.now().plusMinutes(5).toDate(); + query = Query.query(Criteria.where("states.blocked.to").gt(min5Later)); + List blockedDevices = this.mongoTemplate.find(query, Device.class); + blockedDevices.forEach((device) -> this.sessionManager.block(device)); + query = Query.query(Criteria.where("states.blocked.to").lte(min5Later)); + List unblockedDevices = this.mongoTemplate.find(query, Device.class); + this.mongoTemplate.updateMulti(query, (new Update()).unset("states.blocked"), ua_parser.Device.class); + unblockedDevices.forEach((device) -> this.logService.save((User)null, device.getUuid(), "event", "Unblocked by timeout.")); + Update update = new Update(); + update.unset("states.isOnline"); + this.mongoTemplate.updateMulti(new Query(), update, Device.class); + } + + public boolean exists(UUID deviceUuid) { + return this.existsById(Device.class, deviceUuid); + } + + private JsonObject groupByResultToJson(AggregationResults groupByPlatforms) { + if (groupByPlatforms != null && groupByPlatforms.getMappedResults().size() > 0) { + JsonObject jPlatform = new JsonObject(); + + for(GroupByResult result : groupByPlatforms.getMappedResults()) { + String groupName = result.getGroup(); + if (Strings.isNullOrEmpty(groupName)) { + groupName = "unknown"; + } + + int count = result.getCount(); + if (jPlatform.has(groupName)) { + count += jPlatform.get(groupName).getAsInt(); + } + + jPlatform.addProperty(groupName, count); + } + + return jPlatform; + } else { + return null; + } + } + + public long countByDeviceGroupUuid(UUID groupUuid) { + return this.mongoTemplate.count(Query.query(Criteria.where("deviceGroup.$id").is(groupUuid)), Device.class); + } + + public void save(DeviceNote note) { + this.saveDocument(note); + } + + public void delete(UUID noteUuid) { + this.deleteById(DeviceNote.class, noteUuid); + } + + public List getRecentNotes(UUID deviceUuid) { + Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); + query.limit(5); + query.with(Sort.by(Direction.DESC, new String[]{"registeredAt"})); + List notes = this.mongoTemplate.find(query, DeviceNote.class); + + for(DeviceNote note : notes) { + User user = this.userService.findUserByUserUuid(note.getWriterUuid()); + note.setWriter(user); + } + + return notes; + } + + public List getNotes(UUID deviceUuid) { + Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); + query.with(Sort.by(new String[]{"registeredAt"})); + List notes = this.mongoTemplate.find(query, DeviceNote.class); + + for(DeviceNote note : notes) { + User user = this.userService.findUserByUserUuid(note.getWriterUuid()); + note.setWriter(user); + } + + return notes; + } + + public Page getNotes(UUID deviceUuid, Integer pageNum, Integer size) { + Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); + long total = this.mongoTemplate.count(query, DeviceNote.class); + PageRequest pageRequest = PageRequest.of(pageNum, size); + query.with(Sort.by(new String[]{"registeredAt"})); + query.with(pageRequest); + query.collation(LocaleConst.COLLATION_DEFAULT); + List notes = this.mongoTemplate.find(query, DeviceNote.class); + + for(DeviceNote note : notes) { + User user = this.userService.findUserByUserUuid(note.getWriterUuid()); + note.setWriter(user); + } + + return new PageImpl(notes, pageRequest, total); + } + + public DeviceGroup save(DeviceGroup group) { + if (group.getUuid() == null) { + group.init(); + } + + return (DeviceGroup)this.saveDocument(group); + } + + public String getGroupPath(DeviceGroup group) { + List groups = this.getDeviceGroupTree(group); + List names = (List)groups.stream().map((groupElement) -> groupElement.getName()).collect(Collectors.toList()); + String groupPath = Joiner.on("/").join(names); + return groupPath; + } + + public DeviceGroup findDeviceGroup(UUID groupUuid) { + return groupUuid == null ? null : (DeviceGroup)this.findById(DeviceGroup.class, groupUuid); + } + + public DeviceGroup findDeviceGroup(UUID siteUuid, String path, boolean addIfNotExist) { + if (McStringUtils.isNullOrEmpty(path)) { + return null; + } else { + String[] elements = path.split(Pattern.quote("/")); + DeviceGroup group = null; + + for(int i = 0; i < elements.length; ++i) { + String name = elements[i].trim(); + DeviceGroup curGroup = this.findDeviceGroup(siteUuid, group, name); + if (curGroup == null) { + if (!addIfNotExist) { + return null; + } + + group = this.save(new DeviceGroup(siteUuid, group == null ? null : group.getUuid(), name)); + } else { + group = curGroup; + } + } + + return group; + } + } + + public DeviceGroup findDeviceGroupByName(UUID siteUuid, String name) { + if (siteUuid == null) { + return null; + } else { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("profile.name").is(name); + Query query = new Query(criteria); + return (DeviceGroup)this.mongoTemplate.findOne(query, DeviceGroup.class); + } + } + + private DeviceGroup findDeviceGroup(UUID siteUuid, DeviceGroup parent, String childName) { + if (siteUuid == null) { + return null; + } else { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("profile.name").is(childName); + if (parent == null) { + criteria.and("parentUuid").isNull(); + } else { + criteria.and("parentUuid").is(parent.getUuid()); + } + + return (DeviceGroup)this.mongoTemplate.findOne(Query.query(criteria), DeviceGroup.class); + } + } + + public List findAllDeviceGroups(UUID siteUuid, boolean needCount) { + Sort sort = Sort.by(new String[]{"parentUuid"}).and(Sort.by(new String[]{"order"})).and(Sort.by(new String[]{"profile.name"})); + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + query.with(sort); + List deviceGroups = this.mongoTemplate.find(query, DeviceGroup.class); + if (!deviceGroups.isEmpty() && needCount) { + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match((new Criteria()).andOperator(new Criteria[]{Criteria.where("siteUuid").is(siteUuid), Criteria.where("deviceGroup").exists(true)})), Aggregation.group(new String[]{"deviceGroup"}).count().as("count")}); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, Device.class, Document.class); + Map groupMap = new HashMap(); + MapUtils.populateMap(groupMap, deviceGroups, GeneralProfile::getUuid); + results.forEach((result) -> { + DBRef dbRef = (DBRef)result.get("_id"); + if (dbRef != null) { + UUID groupUuid = (UUID)dbRef.getId(); + if (groupMap.containsKey(groupUuid)) { + Integer count = result.getInteger("count"); + ((DeviceGroup)groupMap.get(groupUuid)).setDeviceNumbers(count); + } + } + + }); + } + + return deviceGroups; + } + + public List getDeviceGroupTree(DeviceGroup group) { + List groups = new ArrayList(); + if (group == null) { + return groups; + } else { + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("_id").is(group.getUuid())), Aggregation.graphLookup("deviceGroup").startWith(new String[]{"parentUuid"}).connectFrom("parentUuid").connectTo("_id").depthField("depth").as("parents"), Aggregation.unwind("parents"), Aggregation.sort(Sort.by(Direction.DESC, new String[]{"parents.depth"})).and(Sort.by(Direction.DESC, new String[]{"profile.name"})), Aggregation.group(new String[]{"id"}).push("parents").as("parents")}); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceGroup.class, Document.class); + results.forEach((result) -> { + List parentGroups = result.getList("parents", Document.class); + parentGroups.forEach((parent) -> { + new DeviceGroup(); + DeviceGroup deviceGroup = (DeviceGroup)this.convertToObject(DeviceGroup.class, parent); + groups.add(deviceGroup); + }); + }); + groups.add(group); + return groups; + } + } + + public Set findDevieGroupUuids(UUID... uuids) { + return this.findDevieGroupUuids((Set)Sets.newHashSet(uuids)); + } + + public Set findDevieGroupUuids(Set uuids) { + if (uuids != null && !uuids.isEmpty()) { + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("_id").in(uuids)), Aggregation.graphLookup("deviceGroup").startWith(new String[]{"$_id"}).connectFrom("_id").connectTo("parentUuid").as("children"), Aggregations.newOperation("{$group: {_id: null, uuids: {$addToSet: '$_id'}, children: {$addToSet: '$children._id'}}}"), Aggregations.newOperation("{$project: {_id: 0, uuids: 1, childUuids: {$reduce: {input: '$children', initialValue: [], in: {$concatArrays: ['$$value', '$$this']}}}}}"), Aggregations.newOperation("{$project: {uuids: {$concatArrays: ['$uuids', '$childUuids']}}}")}); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceGroup.class, Document.class); + Iterator it = results.iterator(); + if (it.hasNext()) { + DbObject result = new DbObject((Map)it.next()); + return new HashSet(result.getList("uuids", UUID.class)); + } else { + return null; + } + } else { + return null; + } + } + + public long getDeviceCount(UUID siteUuid) { + return this.mongoTemplate.count(Query.query(Criteria.where("siteUuid").is(siteUuid)), Device.class); + } + + public long getChildDeviceCount(Site site) { + if (!site.isReseller()) { + return 0L; + } else { + List childSites = this.siteService.findAllChilds(site); + if (childSites.size() == 0) { + return 0L; + } else { + Criteria[] criterias = new Criteria[childSites.size()]; + + for(int i = 0; i < childSites.size(); ++i) { + criterias[i] = Criteria.where("siteUuid").is(((Site)childSites.get(i)).getUuid()); + } + + Criteria criteria = (new Criteria()).orOperator(criterias); + Query query = Query.query(criteria); + return this.mongoTemplate.count(query, Device.class); + } + } + } + + public Page findUserGroup(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + List result = this.find(DeviceGroup.class, filter, sortBy, direction); + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public void delete(DeviceGroup group) { + if (group != null && group.getUuid() != null) { + for(DeviceGroup childGroup : this.findChildGroups(group.getUuid())) { + this.delete(childGroup); + } + + this.mongoTemplate.updateMulti(new Query(Criteria.where("deviceGroup.$id").is(group.getUuid())), (new Update()).unset("deviceGroup"), Device.class); + this.deleteById(DeviceGroup.class, group.getUuid()); + } + } + + public int clearGroupIfNotExists() { + List devices = this.findAll(Device.class); + int i = 0; + + for(Device device : devices) { + if (device.getDeviceGroup() != null && !this.existsById(DeviceGroup.class, device.getDeviceGroup().getUuid())) { + i = (int)((long)i + this.unsetDeviceGroup(device)); + } + } + + return i; + } + + public DeviceApps getApps(UUID deviceUuid) { + return (DeviceApps)this.findById(DeviceApps.class, deviceUuid); + } + + public List getClients() { + return null; + } + + public boolean hasInstalledApp(UUID deviceUuid) { + Criteria criteria = Criteria.where("_id").is(deviceUuid).and("category").is("installed"); + return this.mongoTemplate.exists(Query.query(criteria), DeviceApps.class); + } + + public Document installedApp(UUID deviceUuid, String packageName, int versionCode, String versionName) { + Document document = (new Document("deviceUuid", deviceUuid)).append("packageName", packageName); + Criteria criteria = Criteria.where("_id").is(deviceUuid).and("apps.packageName").is(packageName); + if (versionCode > 0) { + criteria.and("apps.versionCode").is(versionCode); + document.append("versionCode", versionCode); + } + + if (!Strings.isNullOrEmpty(versionName)) { + criteria.and("apps.versionName").is(versionName); + document.append("versionName", versionName); + } + + Query query = Query.query(criteria); + boolean installed = this.mongoTemplate.exists(query, DeviceApps.class); + document.append("installed", installed); + return document; + } + + public boolean newClientAppInstalled(UUID deviceUuid) { + DeviceApps apps = this.getApps(deviceUuid); + if (apps == null) { + return false; + } else { + AppInfo appInfo = apps.getClientService(); + if (appInfo == null) { + return false; + } else { + int versionCode = appInfo.getVersionCode(); + return versionCode >= 1030 || versionCode < 1000 && versionCode > 220; + } + } + } + + public void setClientVersion(UUID deviceUuid, int clientVersion) { + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(deviceUuid)), Update.update("states.clientVersion", clientVersion), Device.class); + } + + public void resetDevice(Device device, boolean isDelete) { + UUID deviceUuid = device.getUuid(); + if (!isDelete) { + device.reset(); + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(device.getUuid())), (new Update()).unset("states").unset("enrolled"), Device.class); + } + + this.deviceAppsService.delete(deviceUuid); + this.deviceReportService.resetDevice(deviceUuid); + if (isDelete) { + this.logService.clearAllLogsFor(deviceUuid); + } + + String deviceFilePath = Joiner.on('/').join(this.settingsService.getFilesRootPath(), device.getSiteUuid(), new Object[]{"device", deviceUuid}); + (new McFile(deviceFilePath)).delete(); + } + + public DeviceLicense save(DeviceLicense license) { + return (DeviceLicense)this.saveDocument(license); + } + + public List saveDeviceLicenses(List licenses) { + return this.deviceLicenseRepository.saveAll(licenses); + } + + public List findAllLicenses(Site site) { + if (site == null) { + return this.findAll(DeviceLicense.class); + } else { + String key = site.isChild() ? "childSite" : "site"; + key = key + ".$id"; + Query query = Query.query(Criteria.where(key).is(site.getUuid())); + return this.mongoTemplate.find(query, DeviceLicense.class); + } + } + + public Page findLicenses(Site site, LicenseModel licenseModel, String plan, boolean licensed, JsonObject jFilter, Integer page, Integer size, String sortBy, Sort.Direction direction, Integer expiry) { + Pageable pageable = PageRequest.of(page, size); + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "expiry"; + direction = Direction.DESC; + } + + Query query = new Query(); + if (site.isChild()) { + query.addCriteria(Criteria.where("site.$id").is(site.getReseller().getUuid()).and("childSite.$id").is(site.getUuid())); + } else { + query.addCriteria(Criteria.where("site.$id").is(site.getUuid())); + if (licenseModel == null && Strings.isNullOrEmpty(McJsonUtils.getString(jFilter, "deviceSerial"))) { + if (licensed) { + query.addCriteria(Criteria.where("childSite").exists(true)); + } + } else { + query.addCriteria(Criteria.where("childSite").exists(false)); + } + } + + if (jFilter != null && jFilter.size() > 0) { + for(String key : jFilter.keySet()) { + String value = jFilter.get(key).getAsString(); + if (!Strings.isNullOrEmpty(value)) { + Criteria criteria = null; + + try { + UUID uuid = UUID.fromString(value); + criteria = Criteria.where(key).is(uuid); + } catch (Exception var18) { + criteria = McMongoUtils.toLikeCriteria(key, value); + } + + query.addCriteria(criteria); + } + } + } + + if (expiry != null) { + Date now = new Date(); + if (expiry == -1) { + query.addCriteria(Criteria.where("expiry").lt(now)); + } else if (expiry == 0) { + Criteria criteria = (new Criteria()).orOperator(new Criteria[]{Criteria.where("expiry").gte(now), Criteria.where("expiry").exists(false)}); + query.addCriteria(criteria); + } else { + Criteria criteria = (new Criteria()).andOperator(new Criteria[]{Criteria.where("expiry").lt((new DateTime()).plusDays(expiry).toDate()), Criteria.where("expiry").gte(now)}); + query.addCriteria(criteria); + } + } + + if (licenseModel != null) { + query.addCriteria(Criteria.where("licenseModel.$id").is(licenseModel.getUuid())); + } + + if (plan != null) { + query.addCriteria(Criteria.where("plan").is(plan)); + } + + Sort sort = Sort.by(direction, new String[]{sortBy}); + query.with(sort); + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, DeviceLicense.class); + List result = this.mongoTemplate.find(query.with(pageable), DeviceLicense.class); + Page pageResult = new PageImpl(result, pageable, total); + return pageResult; + } + + public List findLicenses(Site site, LicenseModel licenseModel, JsonObject filter, String sortBy, Sort.Direction direction, Integer expiry) { + Query query = new Query(); + if (site.isChild()) { + query.addCriteria(Criteria.where("site.$id").is(site.getReseller().getUuid()).and("childSite.$id").is(site.getUuid())); + } else { + query.addCriteria(Criteria.where("site.$id").is(site.getUuid()).and("childSiteLicense").exists(false)); + } + + if (filter != null) { + JsonElement jFilter = McJsonUtils.toJsonElement(filter); + if (jFilter.isJsonObject()) { + JsonObject jFilterObject = jFilter.getAsJsonObject(); + + for(String key : jFilterObject.keySet()) { + String value = jFilterObject.get(key).getAsString(); + if (!Strings.isNullOrEmpty(value)) { + Criteria criteria = McMongoUtils.toLikeCriteria(key, value); + query.addCriteria(criteria); + } + } + } + } + + if (expiry != null) { + Date now = new Date(); + if (expiry == -1) { + query.addCriteria(Criteria.where("expiry").lt(now)); + } else if (expiry == 0) { + Criteria criteria = (new Criteria()).orOperator(new Criteria[]{Criteria.where("expiry").gte(now), Criteria.where("expiry").exists(false)}); + query.addCriteria(criteria); + } else { + Criteria criteria = (new Criteria()).andOperator(new Criteria[]{Criteria.where("expiry").lt((new DateTime()).plusDays(expiry).toDate()), Criteria.where("expiry").gte(now)}); + query.addCriteria(criteria); + } + } + + if (licenseModel != null) { + query.addCriteria(Criteria.where("licenseModel.$id").is(licenseModel.getUuid())); + } + + List result = this.mongoTemplate.find(query, DeviceLicense.class); + return result; + } + + public List getLicenses(Device device) { + return this.getLicenses(device.getSerialNo()); + } + + public List getLicenses(String serial) { + Query query = Query.query(Criteria.where("deviceSerial").is(serial)); + return this.mongoTemplate.find(query, DeviceLicense.class); + } + + public List getFreshLicenses(UUID siteUuid, String plan, UUID licenseModelUuid, int amount) { + Query query = new Query(); + query.addCriteria(Criteria.where("site.$id").is(siteUuid).and("licenseModel.$id").is(licenseModelUuid).and("plan").is(plan).and("childSite").exists(false).and("deviceUuid").exists(false).and("activatedAt").exists(false).and("expiry").gte(new Date())); + query.with(Sort.by(Direction.ASC, new String[]{"created"})); + query.limit(amount); + List licenses = this.mongoTemplate.find(query, DeviceLicense.class); + return licenses; + } + + public DeviceLicense getTrialLicense(Device device) { + if (this.hostLicenseService.isStandalone()) { + return null; + } else { + DeviceLicense curLicense = device.getLicense(); + if (curLicense != null && curLicense.isTrial()) { + return curLicense; + } else { + DeviceLicense prevLicense = null; + + for(DeviceLicense license : this.getLicenses(device.getSerialNo())) { + if (license.isTrial()) { + prevLicense = license; + break; + } + } + + if (prevLicense != null && prevLicense.beforeExpiry()) { + prevLicense.expire(); + } else { + LicenseModel trialLicenseModel = this.licenseService.getTrialLicenseModel(); + prevLicense = new DeviceLicense(device, trialLicenseModel); + } + + return prevLicense; + } + } + } + + public DeviceLicense setLicense(Device device, String licenseIdName, boolean autoRenew, boolean renewToSameModel) { + LicenseModel model = this.licenseService.findLicenseModelByIdName(licenseIdName); + return model == null ? null : this.setLicense(device, model.getUuid(), true, autoRenew, renewToSameModel); + } + + public void expireAllPreviousLicenses(UUID siteUuid) { + if (siteUuid != null) { + Date expiry = new Date(); + Query query = Query.query(Criteria.where("expiry").gt(expiry).orOperator(new Criteria[]{Criteria.where("site.$id").is(siteUuid), Criteria.where("childSite.$id").is(siteUuid)})); + this.mongoTemplate.updateMulti(query, Update.update("expiry", expiry), DeviceLicense.class); + query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("licenseExpiry").gt(expiry)); + this.mongoTemplate.updateMulti(query, Update.update("licenseExpiry", expiry), Device.class); + } + } + + public void updateSerialNo(Device device, String serialNo) { + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(device.getUuid())), Update.update("profile.hardware_info.serial_no", serialNo), Device.class); + if (!this.hostLicenseService.isStandalone()) { + this.mongoTemplate.updateFirst(Query.query(Criteria.where("deviceUuid").is(device.getUuid())), Update.update("deviceSerial", serialNo), DeviceLicense.class); + } + + } + + public DeviceLicense setLicense(Device device, UUID licenseModelUuid, boolean keepModel, boolean autoRenew, boolean renewToSameModel) { + DeviceLicense prevLicense = device.getLicense(); + if (prevLicense != null) { + if (prevLicense.isPerpetual() && prevLicense.isExceedActivationCount()) { + return null; + } + + if (!prevLicense.isTrial() && !device.isLicenseExpired() && (keepModel || licenseModelUuid == null || prevLicense.isSameLicenseModel(licenseModelUuid))) { + boolean updated = false; + if (prevLicense.isAutoRenew() != autoRenew) { + prevLicense.setAutoRenew(autoRenew); + updated = true; + } + + if (prevLicense.isRenewToSameModel() != renewToSameModel) { + prevLicense.setRenewToSameModel(renewToSameModel); + updated = true; + } + + if (updated) { + this.save(prevLicense); + } + + return prevLicense; + } + } + + if (licenseModelUuid == null) { + return prevLicense; + } else { + DeviceLicense license = this.getAvailableLicense(device, licenseModelUuid, renewToSameModel); + if (license == null) { + return null; + } else { + if (prevLicense != null) { + if (license.isTrial()) { + return null; + } + + if (prevLicense.isTrial()) { + if (prevLicense.beforeExpiry()) { + prevLicense.expire(); + this.save(prevLicense); + } + } else { + prevLicense.setAutoRenew(autoRenew); + if (prevLicense.setDevice((Device)null)) { + this.save(prevLicense); + } + } + } else { + DeviceLicense trialLicense = this.setTrialLicense(device); + trialLicense.expire(); + this.save(trialLicense); + } + + license.setAutoRenew(autoRenew); + license.setRenewToSameModel(renewToSameModel); + license.setDevice(device); + license = this.save(license); + device.setLicense(license); + this.save(device); + if (!license.isTrial()) { + this.addLicenseLog(license, device, (Device)null, "apply", "License applied."); + } + + return license; + } + } + } + + public DeviceLicense transferLicense(Device device, Device receiver) { + if (device != null && receiver != null) { + if (device.getUuid().equals(receiver.getUuid())) { + return null; + } else if (receiver.hasLicense() && !receiver.isLicenseExpired() && !receiver.getLicense().isTrial()) { + return null; + } else { + DeviceLicense license = device.getLicense(); + if (license != null && !license.isTrial()) { + this.removeLicense(device); + license.setDevice(receiver); + this.save(license); + receiver.setLicense(license); + this.save(receiver); + this.addLicenseLog(license, device, receiver, "transfer", "License transferred."); + return license; + } else { + return null; + } + } + } else { + return null; + } + } + + public DeviceLicense activateLicense(DeviceLicense license) { + Query query = Query.query(Criteria.where("_id").is(license.getUuid())); + Update update = (new Update()).inc("activationCount", 1); + if (!license.isActivated()) { + license.activate(); + update.set("activatedAt", license.getActivatedAt()).set("expiry", license.getExpiry()); + } + + if (this.mongoTemplate.updateFirst(query, update, DeviceLicense.class).getModifiedCount() > 0L) { + this.mongoTemplate.updateFirst(this.queryById(license.getDeviceUuid()), Update.update("licenseExpiry", license.getExpiry()), Device.class); + return license; + } else { + return null; + } + } + + public UpdateResult resetLicense(DeviceLicense license) { + license.reset(); + Query query = Query.query(Criteria.where("_id").is(license.getUuid())); + Update update = Update.update("autoRenew", false).set("renewToSameModel", false).set("activationCount", license.getActivationCount()).set("expiry", license.getExpiry()).unset("deviceUuid").unset("deviceSerial"); + return this.mongoTemplate.updateFirst(query, update, DeviceLicense.class); + } + + public void setLicenseExpiry(Device device, Date expiry) { + this.updateLicenseExpiry(device, expiry); + this.updateLicenseExpiry(device.getLicense(), expiry, (List)null); + } + + public void updateLicenseExpiry(Device device, Date expiry) { + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(device.getUuid())), Update.update("licenseExpiry", expiry), Device.class); + } + + public void updateLicenseExpiry(DeviceLicense license, Date expiry, List reactivated) { + Update update = Update.update("expiry", expiry); + if (reactivated != null) { + update.set("reactivated", reactivated); + } + + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(license.getUuid())), update, DeviceLicense.class); + } + + public void removeLicense(Device device) { + if (device != null && device.hasLicense()) { + DeviceLicense license = device.getLicense(); + if (license.isExceedActivationCount()) { + return; + } + + license.setDevice((Device)null); + this.saveDocument(license); + device.removeLicense(); + this.addLicenseLog(license, device, (Device)null, "remove", "License removed"); + List licenses = this.getLicenses(device.getSerialNo()); + license = null; + + for(DeviceLicense prevLicense : licenses) { + if (license == null && prevLicense.isTrial() && prevLicense.hasLicenseModel()) { + license = prevLicense; + if (prevLicense.beforeExpiry()) { + prevLicense.setExpiry(new Date()); + } + } else { + prevLicense.setDeviceUuid((UUID)null); + prevLicense.setDeviceSerial((String)null); + this.save(prevLicense); + } + } + + if (license == null) { + license = this.getTrialLicense(device); + license.setDevice(device); + license.setExpiry(new Date()); + } + + this.save(license); + device.setLicense(license); + this.save(device); + this.sessionManager.close(device.getUuid(), CloseStatus.NOT_ACCEPTABLE); + } + + } + + public DeviceLicense resetLicenses(Device device) { + if (device == null) { + return null; + } else { + DeviceLicense license = device.getLicense(); + if (license == null) { + license = this.setTrialLicense(device); + device.setLicense(license); + this.save(device); + } else if (license.isTrial()) { + LicenseModel licenseModel = license.getLicenseModel(); + if (licenseModel == null) { + licenseModel = this.licenseService.getTrialLicenseModel(); + license.setLicenseModel(licenseModel); + } else { + license.extendExpiryDays(license.getLicenseModel().getPeriod()); + } + + license.setActivationCount(0); + device.setLicense(license); + this.save(device); + } else if (license.isExpired()) { + license = this.setTrialLicense(device); + license.setActivationCount(0); + license.extendExpiryDays(license.getLicenseModel().getPeriod()); + device.setLicense(license); + this.save(device); + } else { + license.resetActivationCount(); + } + + this.save(license); + return license; + } + } + + public boolean isLicenseAvailable(Device device) { + if (this.hostLicenseService.isStandalone()) { + return true; + } else if (device.hasLicense()) { + if (!device.isLicenseExpired()) { + return true; + } else { + return device.getLicense().isAutoRenew() && this.renewLicense(device); + } + } else { + DeviceLicense license = this.setTrialLicense(device); + device.setLicense(license); + this.save(device); + return true; + } + } + + public boolean renewLicense(Device device) { + if (device != null && device.hasLicense()) { + DeviceLicense prevLicense = device.getLicense(); + if (prevLicense.isTrial()) { + return false; + } else { + if (!prevLicense.isExpired()) { + prevLicense.expire(); + this.save(prevLicense); + } + + DeviceLicense newLicense = this.getAvailableLicense(device, prevLicense.getLicenseModel().getUuid(), prevLicense.isRenewToSameModel()); + if (newLicense == null) { + return false; + } else { + newLicense.setDevice(device); + newLicense.setAutoRenew(prevLicense.isAutoRenew()); + newLicense.setRenewToSameModel(prevLicense.isRenewToSameModel()); + newLicense = this.save(newLicense); + device.setLicense(newLicense); + this.save(device); + this.addLicenseLog(newLicense, device, (Device)null, "renew", "License renewed."); + return true; + } + } + } else { + return false; + } + } + + public DeviceLicense getAvailableLicense(Device device, UUID licenseModelUuid, boolean sameModelOnly) { + Site site = this.siteService.findByUuid(device.getSiteUuid()); + DeviceLicense license = this.getAvailableLicense(site, licenseModelUuid); + return license == null && !sameModelOnly ? this.getAvailableLicense(site, (UUID)null) : license; + } + + public DeviceLicense getAvailableLicense(Site site, UUID licenseModelUuid) { + Criteria criteria = Criteria.where("plan").is(site.getPlanName()).and("deviceUuid").exists(false).orOperator(new Criteria[]{Criteria.where("expiry").gte(new Date()), Criteria.where("expiry").exists(false)}); + if (licenseModelUuid != null) { + criteria.and("licenseModel.$id").is(licenseModelUuid); + } + + Query query = Query.query(criteria); + if (site.isChild()) { + query.addCriteria(Criteria.where("site.$id").is(site.getReseller().getUuid()).and("childSite.$id").is(site.getUuid())); + } else { + query.addCriteria(Criteria.where("site.$id").is(site.getUuid()).and("childSite").exists(false)); + } + + Sort sort = Sort.by(Direction.ASC, new String[]{"expiry"}); + query.with(sort); + DeviceLicense license = (DeviceLicense)this.mongoTemplate.findOne(query, DeviceLicense.class); + return license; + } + + public void addLicenseLog(DeviceLicense license, Device from, Device to, String activity, String message) { + MidmLog addLog = new MidmLog(); + addLog.setForWhat(license.getChildSite() == null ? license.getSite().getUuid() : license.getChildSite().getUuid()); + addLog.setCategory("license"); + addLog.setLog(message); + addLog.addReference("activity", activity); + if (from != null) { + addLog.addReference("from", from.getSerialNo()); + } + + if (to != null) { + addLog.addReference("to", to.getSerialNo()); + } + + DbObject licenseObject = new DbObject(); + licenseObject.put("uuid", license.getUuid()); + licenseObject.put("model", license.getLicenseModel()); + addLog.addReference("license", licenseObject); + this.logService.save(addLog); + } + + @Scheduled( + cron = "0 5 0 * * *" + ) + @Async + public void validateLicenseTask() { + if (!this.hostLicenseService.isStandalone() && this.hostLicenseService.isPrimaryServer()) { + Date from = LocalDate.now().minusDays(1).toDate(); + Date to = new Date(); + + for(Device device : this.mongoTemplate.find(Query.query((new Criteria()).andOperator(new Criteria[]{Criteria.where("licenseExpiry").gte(from), Criteria.where("licenseExpiry").lt(to)})), Device.class)) { + if (device.isLicenseExpired()) { + if (device.getLicense().isAutoRenew()) { + if (this.sessionManager.isOnline(device.getUuid())) { + this.renewLicense(device); + } + } else if (this.sessionManager.isOnline(device.getUuid())) { + this.sessionManager.close(device.getUuid(), CloseStatus.NOT_ACCEPTABLE); + } + } + } + + } + } + + public long getDeviceStat(UUID siteUuid, String filter, String field) { + Query query = new Query(); + Criteria andCriteria = new Criteria(); + Criteria criteria = new Criteria(); + switch (DeviceService.KEY.get(field)) { + case enrolled: + criteria = Criteria.where("enrolled").exists(true); + break; + case disabled: + criteria = Criteria.where("enabled").is(false); + break; + case license_expired: + criteria = Criteria.where("licenseExpiry").lt(new Date()); + break; + case inactive: + criteria.orOperator(new Criteria[]{Criteria.where("enabled").is(false), Criteria.where("enrolled").exists(false).and("enabled").exists(true), Criteria.where("licenseExpiry").lt(new Date()).and("enrolled").exists(true).and("enabled").is(true)}); + break; + case online: + criteria = Criteria.where("states.isOnline").is(true); + } + + andCriteria.andOperator(new Criteria[]{this.getDeviceCriteria(siteUuid, filter), criteria}); + query.addCriteria(andCriteria); + Long total = this.mongoTemplate.count(query, Device.class); + return total; + } + + public JsonObject getDeviceStateGroup(UUID siteUuid, String filter, String field) { + Criteria andCriteria = null; + Criteria criteria = null; + String statField = ""; + new JsonObject(); + switch (DeviceService.KEY.get(field)) { + case model: + statField = "profile.hardware_info.model"; + break; + case model_online: + statField = "profile.hardware_info.model"; + criteria = Criteria.where("states.isOnline").is(true); + break; + case os: + statField = "profile.software_info.os_version"; + break; + case carrier: + statField = "profile.network.telephony.carrier"; + break; + case battery_condition: + statField = "states.batteryCondition"; + } + + if (criteria != null) { + andCriteria = new Criteria(); + andCriteria.andOperator(new Criteria[]{this.getDeviceCriteria(siteUuid, filter), criteria}); + } else { + andCriteria = this.getDeviceCriteria(siteUuid, filter); + } + + JsonObject jModelType = this.groupBy(statField, andCriteria); + return jModelType; + } + + public long getDeviceTotal(UUID siteUuid, String filter) { + Query query = new Query(); + query.addCriteria(this.getDeviceCriteria(siteUuid, filter)); + Long total = this.mongoTemplate.count(query, Device.class); + return total; + } + + public Criteria getDeviceCriteria(UUID siteUuid, String filter) { + Criteria criteriaSite = Criteria.where("siteUuid").is(siteUuid); + Criteria criteriaFilter = toCriteria(filter); + return Strings.isNullOrEmpty(filter) ? criteriaSite : (new Criteria()).andOperator(new Criteria[]{criteriaFilter, criteriaSite}); + } + + public static Criteria toCriteria(String jFilter) { + return Strings.isNullOrEmpty(jFilter) ? new Criteria() : toCriteria(McJsonUtils.toJsonElement(jFilter).getAsJsonObject()); + } + + public static Criteria toCriteria(JsonObject jFilter) { + List criterias = new ArrayList(); + + for(Map.Entry entry : jFilter.entrySet()) { + String key = (String)entry.getKey(); + JsonElement jValue = (JsonElement)entry.getValue(); + if (key.equalsIgnoreCase("deviceGroup.uuid")) { + key = "deviceGroup.$id"; + if (jValue.isJsonArray() && jValue.getAsJsonArray().size() > 0) { + JsonArray jItems = jValue.getAsJsonArray(); + List subCriterias = new ArrayList(); + + for(JsonElement jItem : jItems) { + String item = jItem.getAsString(); + + try { + UUID uuid = UUID.fromString(item); + subCriterias.add(Criteria.where(key).is(uuid)); + } catch (Exception var12) { + subCriterias.add(Criteria.where(key).regex(Pattern.compile(item, 66))); + } + } + + criterias.add((new Criteria()).orOperator((Criteria[])subCriterias.toArray(new Criteria[0]))); + } else { + criterias.add(Criteria.where(key).exists(false)); + } + } else if (key.equalsIgnoreCase("profile.hardware_info.model")) { + criterias.add(Criteria.where(key).is(jValue.getAsString())); + } else if (key.equalsIgnoreCase("profile.software_info.os_version")) { + if (jValue.getAsString().equals("unknown")) { + criterias.add(Criteria.where(key).exists(false)); + } else { + criterias.add(Criteria.where(key).is(jValue.getAsString())); + } + } else if (key.equalsIgnoreCase("licenseExpiry")) { + int expiry = jValue.getAsInt(); + new Criteria(); + switch (expiry) { + case 10: + case 30: + case 45: + criterias.add(Criteria.where("licenseExpiry").lt((new DateTime()).plusDays(expiry).toDate())); + criterias.add(Criteria.where("licenseExpiry").gte(new Date())); + break; + default: + Criteria subCriterias = (new Criteria()).orOperator(new Criteria[]{Criteria.where("licenseExpiry").gt((new DateTime()).plusDays(45).toDate()), Criteria.where("licenseExpiry").exists(false)}); + criterias.add(subCriterias); + } + } + } + + return (new Criteria()).andOperator((Criteria[])criterias.toArray(new Criteria[0])); + } + + public JsonObject groupBy(String field, Criteria criteria) { + AggregationResults groupByResult = this.groupBy("device", field, criteria); + return this.groupByResultToJson(groupByResult); + } + + public void enableDevicesByGroup(String filter, boolean enabled) { + Query query = new Query(); + Criteria criteriaFilter = McMongoUtils.toCriteria(filter); + query.addCriteria(criteriaFilter); + Update update = Update.update("enabled", enabled).set("updated", new Date()); + UpdateResult result = this.mongoTemplate.updateMulti(query, update, Device.class); + if (!enabled && result.getModifiedCount() > 0L) { + for(Device device : this.mongoTemplate.find(query, Device.class)) { + if (this.sessionManager.isOnline(device.getUuid())) { + this.sessionManager.close(device.getUuid(), CloseStatus.NOT_ACCEPTABLE); + } + } + } + + } + + public void enableDevices(List devices, boolean enabled) { + List criterias = new ArrayList(); + Update update = Update.update("enabled", enabled).set("updated", new Date()); + int nUpdated = 0; + + for(Device device : devices) { + criterias.add(Criteria.where("_id").is(device.getUuid())); + } + + if (!criterias.isEmpty()) { + Criteria criteria = new Criteria(); + criteria.orOperator((Criteria[])criterias.toArray(new Criteria[criterias.size()])); + UpdateResult result = this.mongoTemplate.updateMulti(Query.query(criteria), update, Device.class); + nUpdated = (int)((long)nUpdated + result.getModifiedCount()); + } + + if (!enabled && nUpdated > 0) { + for(Device device : devices) { + if (this.isAuthorized(device)) { + this.sessionManager.close(device.getUuid(), CloseStatus.NOT_ACCEPTABLE); + } + } + } + + } + + public void enableDevice(Device device, boolean enabled) { + if (enabled != device.getEnabled()) { + this.enableDevice(device.getUuid(), enabled); + } + + } + + public void enableDevice(UUID siteUuid, List deviceUuids, boolean enabled) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("_id").in(deviceUuids)); + Update update = Update.update("enabled", enabled); + this.mongoTemplate.updateMulti(query, update, Device.class); + if (!enabled) { + deviceUuids.forEach((uuid) -> this.sessionManager.close(uuid, CloseStatus.NOT_ACCEPTABLE)); + } + + } + + public void enableDevice(UUID deviceUuid, boolean enabled) { + Query query = Query.query(Criteria.where("_id").is(deviceUuid)); + Update update = Update.update("enabled", enabled).set("updated", new Date()); + this.mongoTemplate.updateFirst(query, update, Device.class); + if (!enabled && this.sessionManager.isOnline(deviceUuid)) { + this.sessionManager.close(deviceUuid, CloseStatus.NOT_ACCEPTABLE); + } + + } + + public boolean isAuthorized(Device device, UUID siteUuid) { + return device.getSiteUuid().equals(siteUuid) && this.isAuthorized(device); + } + + public boolean isAuthorized(Device device) { + return device != null && device.getEnabled() && device.isEnrolled() && this.sessionManager.isOnline(device.getUuid()); + } + + public String qrTemplate(User user, String code, boolean print) { + String src = McBase64.fromBase64ToString(code); + JsonElement jParams = McJsonUtils.toJsonElement(src); + String ecrypted = this.encrypt(src); + byte[] bytes = McStringUtils.toBytes(ecrypted); + + try { + BufferedImage image = QrCode.toImage(new String(bytes, "ISO-8859-1"), 200, 0); + byte[] data = QrCode.toBytes(image, "png"); + Context context = new Context(); + context.setVariable("site", user.getSite()); + context.setVariable("params", jParams); + context.setVariable("print", print); + context.setVariable("qrCode", McBase64.toBase64(data)); + return this.emailService.toHtmlContent(context, "qrRegister"); + } catch (UnsupportedEncodingException var11) { + return null; + } + } + + public String encrypt(String source) { + String tokenPassword = "MiDM@MiTAC.com"; + String tokenSalt = "597bf471358daf9c"; + McTextEncryptor encryptor = new McTextEncryptor("MiDM@MiTAC.com", "597bf471358daf9c"); + return encryptor.encrypt(source); + } + + public boolean hasRoamingProblem(long clientVersion) { + return roamingProblemClientVersions.contains(clientVersion); + } + + public boolean hasDateTimeProblem(long clientVersion) { + if (clientVersion > 1000L) { + return clientVersion >= 1087L && clientVersion <= 1090L; + } else { + return clientVersion >= 240L && clientVersion <= 243L; + } + } + + @Async + public void clearOrphans() { + LookupOperation lookupOp = Aggregation.lookup("site", "siteUuid", "_id", "site"); + MatchOperation matchOp = Aggregation.match(Criteria.where("site").size(0)); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{lookupOp, matchOp}); + AggregationResults orphenDevices = this.mongoTemplate.aggregate(aggregation, Device.class, Device.class); + orphenDevices.forEach((device) -> this.delete(device, true)); + lookupOp = Aggregation.lookup("device", "_id", "_id", "device"); + matchOp = Aggregation.match(Criteria.where("device").size(0)); + aggregation = Aggregation.newAggregation(new AggregationOperation[]{lookupOp, matchOp}); + AggregationResults orphenDeviceApps = this.mongoTemplate.aggregate(aggregation, DeviceApps.class, DeviceApps.class); + orphenDeviceApps.forEach((deviceApps) -> this.deviceAppsService.delete(deviceApps.getDeviceUuid())); + } + + public static enum KEY { + device, + battery_condition, + profile, + site, + site_license, + license, + user, + enrolled, + disabled, + license_expired, + inactive, + model, + model_online, + os, + carrier, + online, + install_error, + trial, + normal, + unknown; + + public static KEY get(String key) { + try { + return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); + } catch (Exception var2) { + return unknown; + } + } + } +} diff --git a/src/main/java/com/midm/service/device/DevicesParser.java b/src/main/java/com/midm/service/device/DevicesParser.java new file mode 100644 index 0000000..893339c --- /dev/null +++ b/src/main/java/com/midm/service/device/DevicesParser.java @@ -0,0 +1,458 @@ +package com.midm.service.device; + +import com.google.common.base.Strings; +import com.midm.model.IF_EXISTS_OPTION; +import com.midm.model.device.DEVICE_PROPERTY; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceLicense; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.service.org.UserService; +import com.midm.service.system.LicenseService; +import com.mitac.cell.doc.ExcelCell; +import com.mitac.cell.doc.ExcelRow; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McEmailUtils; +import com.mitac.cell.utils.McStringUtils; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.bson.Document; +import org.springframework.web.multipart.MultipartFile; + +public class DevicesParser { + private UserService userService; + private DeviceService deviceService; + private LicenseService licenseService; + private Map columns = null; + private Map users = new HashMap(); + private Map deviceGroups = new HashMap(); + private Map licenseModels = new HashMap(); + private UUID siteUuid; + private boolean isStandalone; + private List devices = new ArrayList(); + private int serialNoColumnIndex = -1; + private int ifExistsOptionColumnIndex = -1; + + public DevicesParser(boolean isStandalone, UUID siteUuid, UserService userService, DeviceService deviceService, LicenseService licenseService) { + this.isStandalone = isStandalone; + this.siteUuid = siteUuid; + this.deviceService = deviceService; + this.userService = userService; + this.licenseService = licenseService; + } + + public String parse(MultipartFile file) { + String fileType = file.getContentType(); + String fileName = file.getOriginalFilename(); + + try { + List returnValues = null; + if (!fileName.endsWith(".xls") && !fileType.equals(McFile.CONTENT_TYPE_XLS) && !fileType.endsWith(".xls")) { + if (fileName.endsWith(".xlsx") || fileType.equals(McFile.CONTENT_TYPE_XLSX) || fileType.endsWith(".xlsx")) { + returnValues = this.parseXlsx(file.getInputStream()); + } + } else { + returnValues = this.parseXls(file.getInputStream()); + } + + return returnValues != null && returnValues.get(0) instanceof Device ? MidmResponse.getSucceedResponse(returnValues) : MidmResponse.getResponse(404, "Parsing error", returnValues); + } catch (IOException e) { + e.printStackTrace(); + return MidmResponse.getFailedResponse(); + } + } + + private List parseXls(InputStream is) { + List returnValues = null; + + try { + HSSFWorkbook wb = new HSSFWorkbook(is); + returnValues = this.parseSheets(wb.sheetIterator()); + wb.close(); + } catch (IOException var4) { + } + + return returnValues; + } + + private List parseXlsx(InputStream is) { + List returnValues = null; + + try { + XSSFWorkbook wb = new XSSFWorkbook(is); + returnValues = this.parseSheets(wb.sheetIterator()); + wb.close(); + } catch (IOException var4) { + } + + return returnValues; + } + + private List parseSheets(Iterator sheets) { + long curCount = this.deviceService.count(Device.class); + int limit = this.deviceService.getDeviceLimit(); + List exceptions = new ArrayList(); + + while(sheets.hasNext()) { + Sheet sheet = (Sheet)sheets.next(); + Iterator rows = sheet.rowIterator(); + + while(rows.hasNext()) { + try { + Device device = this.parseRow((Row)rows.next()); + if (device != null) { + if (limit > 0 && ++curCount > (long)limit) { + exceptions.add(new MidmParseException(421, "The devices will be exceeded the device limit.")); + break; + } + + this.devices.add(device); + } + } catch (MidmParseException e) { + exceptions.add(e); + if (this.serialNoColumnIndex < 0) { + break; + } + } + } + } + + if (exceptions.isEmpty()) { + this.deviceService.saveDevices(this.devices); + return this.devices; + } else { + return exceptions; + } + } + + private Device parseRow(Row row) throws MidmParseException { + Iterator cells = row.cellIterator(); + String licenseType = ""; + Boolean autoRenew = null; + Boolean renewToSameModel = false; + if (row.getRowNum() == 0) { + this.columns = new HashMap(); + + while(cells.hasNext()) { + Cell cell = (Cell)cells.next(); + String value = cell.getStringCellValue(); + if (McStringUtils.isValid(value)) { + DEVICE_PROPERTY property = DEVICE_PROPERTY.get(value); + this.columns.put(cell.getColumnIndex(), property); + if (property != DEVICE_PROPERTY.serialno && property != DEVICE_PROPERTY.serial_no && property != DEVICE_PROPERTY.product_sn && property != DEVICE_PROPERTY.productsn && property != DEVICE_PROPERTY.serial_number && property != DEVICE_PROPERTY.serialnumber) { + if (property == DEVICE_PROPERTY.exists || property == DEVICE_PROPERTY.if_exists || property == DEVICE_PROPERTY.ifexists) { + this.ifExistsOptionColumnIndex = this.columns.size() - 1; + } + } else { + this.serialNoColumnIndex = this.columns.size() - 1; + } + } + } + + if (this.serialNoColumnIndex < 0) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "No serial number column found."); + } else { + return null; + } + } else if (ExcelRow.isEmpty(row)) { + return null; + } else { + Cell serialNoCell = row.getCell(this.serialNoColumnIndex); + if (serialNoCell != null && !ExcelCell.isEmpty(serialNoCell)) { + if (serialNoCell.getCellType() != CellType.STRING) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "Serial number cell must be text."); + } else { + String serialNo = serialNoCell.getStringCellValue().trim(); + if (serialNo != null && serialNo.length() >= 4) { + boolean isDuplicated = this.devices.stream().anyMatch((deviceItem) -> deviceItem.getSerialNo().equals(serialNo)); + if (isDuplicated) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "Duplicated serial number:" + serialNo); + } else { + Device existDevice = this.deviceService.findBySerialNo(serialNo); + if (existDevice != null && !existDevice.getSiteUuid().equals(this.siteUuid)) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "The device " + serialNo + " is existing in other site."); + } else { + IF_EXISTS_OPTION ifExistOption = IF_EXISTS_OPTION.skip; + if (this.ifExistsOptionColumnIndex >= 0) { + Cell ifExistsOptionCell = row.getCell(this.ifExistsOptionColumnIndex); + if (ifExistsOptionCell != null) { + String option = ifExistsOptionCell.getStringCellValue(); + ifExistOption = IF_EXISTS_OPTION.get(option); + } + } + + if (ifExistOption == IF_EXISTS_OPTION.remove) { + if (existDevice == null) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "Not exist serial number:" + serialNo); + } else { + DeviceLicense license = existDevice.getLicense(); + if (license.getActivationCount() >= license.getLicenseModel().getMaxActivation()) { + this.deviceService.retireDeviceLicense(existDevice); + } + + this.deviceService.delete(existDevice, false); + return null; + } + } else { + Device device = null; + if (existDevice != null) { + if (ifExistOption.option == 0) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "The device is already exist ."); + } + + if (ifExistOption.option == 1) { + this.deviceService.delete(existDevice, false); + } else if (ifExistOption.option == 2) { + device = existDevice; + } + } + + if (device == null) { + device = new Device(); + device.init(); + device.setSerialNo(serialNo); + device.setSiteUuid(this.siteUuid); + device.setEnabled(true); + } + + while(cells.hasNext()) { + Cell cell = (Cell)cells.next(); + CellType cellType = cell.getCellType(); + DEVICE_PROPERTY property = (DEVICE_PROPERTY)this.columns.get(cell.getColumnIndex()); + if (property != null && !ExcelCell.isEmpty(cell)) { + if (cellType != CellType.STRING) { + if (property != DEVICE_PROPERTY.renew) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), property + " cell must be text."); + } + + if (cellType == CellType.BOOLEAN) { + autoRenew = cell.getBooleanCellValue(); + } else { + if (cellType != CellType.NUMERIC) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), property + " cell must be text or boolean."); + } + + autoRenew = cell.getNumericCellValue() != (double)0.0F; + } + } else { + String value = cell.getStringCellValue(); + if (!McStringUtils.isNullOrEmpty(value)) { + switch (property) { + case partno: + case part_no: + device.setProfile("shipment", "part_no", value); + break; + case palletno: + case pallet_no: + device.setProfile("shipment", "pallet_mo", value); + break; + case cartonsn: + case carton_sn: + device.setProfile("shipment", "carton_no", value); + break; + case wifimac: + case wifi_mac: + device.setProfile("network", "wifi_mac", value); + break; + case device_group: + case devicegroup: + case group: + DeviceGroup deviceGroup = this.findDeviceGroup(value); + if (deviceGroup == null) { + throw DevicesParser.MidmParseException.genException(405, row.getRowNum(), "No group: " + value); + } + + device.setDeviceGroup(deviceGroup); + break; + case owner: + try { + device.setOwner((User)null); + Document owner = Document.parse(value); + if (owner != null && !owner.isEmpty()) { + String email = owner.getString("email"); + if (!Strings.isNullOrEmpty(email)) { + if (!McEmailUtils.isValid(email)) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "Email format is incorrect."); + } + + User existUser = this.findUser(email); + if (existUser != null && existUser.isBelongedToSite(this.siteUuid)) { + device.setOwner(existUser); + } + } + + device.setProfile("owner", owner); + } + break; + } catch (Exception var20) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "Owner column must be JSON formatted."); + } + case owner_name: + if (!device.hasOwner()) { + device.setProfile("owner", "name", value); + } + break; + case owner_phone: + if (!device.hasOwner()) { + device.setProfile("owner", "phone", value); + } + break; + case owner_mobile: + if (!device.hasOwner()) { + device.setProfile("owner", "mobile", value); + } + break; + case owner_email: + case email: + if (!McEmailUtils.isValid(value)) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "Email format is incorrect."); + } + + User owner = this.findUser(value); + if (owner == null) { + device.setProfile("owner", "email", value); + device.setOwner((User)null); + } else if (owner.isBelongedToSite(this.siteUuid)) { + device.setOwner(owner); + } else { + device.setProfile("owner", "email", value); + device.setOwner((User)null); + } + break; + case description: + case desc: + case comment: + case memo: + device.setProfile("comment", value); + break; + case license: + if (!Strings.isNullOrEmpty(value) && !this.isStandalone) { + licenseType = value; + } + break; + case renew: + autoRenew = !Strings.isNullOrEmpty(value) && (value.trim().equalsIgnoreCase("auto") || value.equalsIgnoreCase("true")); + break; + case renewtosamemodel: + case renew_to_same_model: + renewToSameModel = !Strings.isNullOrEmpty(value) && value.equalsIgnoreCase("true"); + break; + case rsa: + device.setRsa(value.trim()); + } + } + } + } + } + + if (!Strings.isNullOrEmpty(licenseType) && !licenseType.equals("trial")) { + if (autoRenew == null) { + autoRenew = false; + } + + DeviceLicense prevLicense = device.getLicense(); + DeviceLicense deviceLicense = null; + LicenseModel model = this.findLicenseModel(licenseType); + if (model == null) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "There's no " + licenseType + " exists."); + } + + deviceLicense = this.deviceService.getAvailableLicense(device, model.getUuid(), renewToSameModel); + if (prevLicense != null && !prevLicense.isTrial()) { + this.deviceService.setLicense(device, model.getUuid(), false, autoRenew, renewToSameModel); + } else { + if (deviceLicense == null) { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "There's no available " + licenseType + " license."); + } + + if (prevLicense != null && prevLicense.isTrial()) { + prevLicense.expire(); + this.deviceService.save(prevLicense); + } + + deviceLicense.setDevice(device); + deviceLicense.setAutoRenew(autoRenew); + deviceLicense.setRenewToSameModel(renewToSameModel); + this.deviceService.save(deviceLicense); + device.setLicense(deviceLicense); + } + } else if (autoRenew != null) { + DeviceLicense prevLicense = device.getLicense(); + if (prevLicense.isAutoRenew() != autoRenew && !prevLicense.isTrial()) { + prevLicense.setAutoRenew(autoRenew); + prevLicense.setRenewToSameModel(renewToSameModel); + this.deviceService.save(prevLicense); + } + } + + return device; + } + } + } + } else { + throw DevicesParser.MidmParseException.genException(400, row.getRowNum(), "Serial number length must be at least 4."); + } + } + } else { + throw DevicesParser.MidmParseException.genException(401, row.getRowNum(), "No serial no. defined."); + } + } + } + + public User findUser(String email) { + if (this.users.containsKey(email)) { + return (User)this.users.get(email); + } else { + User user = this.userService.findUserByEmail(email); + this.users.put(email, user); + return user; + } + } + + public DeviceGroup findDeviceGroup(String path) { + if (this.deviceGroups.containsKey(path)) { + return (DeviceGroup)this.deviceGroups.get(path); + } else { + DeviceGroup group = this.deviceService.findDeviceGroup(this.siteUuid, path, true); + this.deviceGroups.put(path, group); + return group; + } + } + + public LicenseModel findLicenseModel(String licenseType) { + if (this.licenseModels.containsKey(licenseType)) { + return (LicenseModel)this.licenseModels.get(licenseType); + } else { + LicenseModel model = this.licenseService.findLicenseModelByIdName(licenseType); + this.licenseModels.put(licenseType, model); + return model; + } + } + + private static class MidmParseException extends Exception { + private static final long serialVersionUID = 1L; + + public MidmParseException(int code, String message) { + super(message); + } + + public static MidmParseException genException(int code, int rowNum, String reason) { + String message = String.format("%d: %s", rowNum, reason); + return new MidmParseException(code, message); + } + } +} diff --git a/src/main/java/com/midm/service/device/MustProfileService.java b/src/main/java/com/midm/service/device/MustProfileService.java new file mode 100644 index 0000000..0f61192 --- /dev/null +++ b/src/main/java/com/midm/service/device/MustProfileService.java @@ -0,0 +1,104 @@ +package com.midm.service.device; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.midm.model.device.DeviceProfile; +import com.midm.service.file.FileService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.io.McZipFile; +import com.mitac.cell.must.MustBuilder; +import com.mitac.cell.utils.McJsonUtils; +import java.io.File; +import java.util.UUID; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class MustProfileService { + @Autowired + private FileService fileService; + + public void build(DeviceProfile profile) { + String root = this.fileService.getMustFolderRootPath(profile.getSiteUuid(), profile.getUuid()); + JsonObject jProfile = McJsonUtils.toJsonElement(profile).getAsJsonObject(); + JsonObject jMust = new JsonObject(); + JsonObject jProfileProfile = jProfile.getAsJsonObject("profile"); + jMust.add("configuration_id", jProfileProfile.get("configuration_id")); + jMust.add("created_date", jProfile.get("created")); + jMust.add("distributor", jProfileProfile.get("distributor")); + jMust.add("platform", jProfileProfile.get("platform")); + jMust.add("script_version", jProfileProfile.get("script_version")); + jMust.add("updated", jProfile.get("created")); + JsonObject jProfileSettings = jProfile.getAsJsonObject("settings"); + jMust.add("system", jProfileSettings.getAsJsonObject("system")); + jMust.add("network", jProfileSettings.getAsJsonObject("network")); + jMust.add("security", jProfileSettings.getAsJsonObject("security")); + jMust.add("browser", jProfileSettings.getAsJsonObject("browser")); + jMust.add("midm", jProfileSettings.getAsJsonObject("midm")); + jMust.add("launcher", jProfileSettings.getAsJsonObject("launcher")); + jMust.add("developer", jProfileSettings.getAsJsonObject("developer")); + jMust.add("otas", jProfileSettings.getAsJsonObject("otas")); + jMust.add("msettings", jProfileSettings.getAsJsonObject("msettings")); + JsonObject jProfileApps = jProfile.getAsJsonObject("apps"); + jMust.add("application", jProfileApps); + MustBuilder builder = new MustBuilder(jMust); + builder.save((new File(root, "must/default.mst")).getPath()); + JsonObject updateInfo = jProfileProfile.getAsJsonObject("updateInfo"); + JsonArray checksumList = this.checksumList(root, (File)null); + updateInfo.add("checksum_list", checksumList); + String updateInfoData = McJsonUtils.toJson(updateInfo, true); + (new McFile(root, "update_info")).write(updateInfoData.getBytes()); + this.compress(profile.getUuid(), root, "region"); + } + + public void compress(UUID profileUuid, String rootPath, String destPath) { + McFile rootFolder = new McFile(rootPath); + if (rootFolder.exists() && !rootFolder.isFile()) { + McZipFile zipFile = new McZipFile(rootFolder.getParent() + "/" + destPath, profileUuid.toString()); + if (zipFile.exists()) { + zipFile.delete(); + } + + zipFile.compress(rootFolder.listFiles()); + } + } + + public void compressSingleFolder(UUID profileUuid, String rootPath, String filePath, String destPath, String folderName) { + McFile rootFolder = new McFile(rootPath); + McFile targetFolder = new McFile(filePath); + if (targetFolder.exists() && !targetFolder.isFile()) { + McZipFile zipFile = new McZipFile(rootFolder.getParent() + "/" + destPath + "/" + profileUuid, folderName); + if (zipFile.exists()) { + zipFile.delete(); + } + + zipFile.compress(targetFolder.listFiles()); + } + } + + public JsonArray checksumList(String root, File parent) { + JsonArray checksumList = new JsonArray(); + McFile file = parent != null ? new McFile(parent) : new McFile(root); + if (!file.exists()) { + return null; + } else { + for(File fileItem : file.listFiles()) { + if (fileItem.isDirectory()) { + if (!fileItem.getName().equals("META-INF")) { + JsonArray checksums = this.checksumList(root, fileItem); + if (checksums != null && checksums.size() > 0) { + checksumList.addAll(checksums); + } + } + } else if (!fileItem.getName().equals("update_info")) { + long size = fileItem.length(); + long checksum = (new McFile(fileItem)).getCrcChecksum(); + String path = fileItem.getPath().substring(root.length()); + checksumList.add(String.format("%d %d .%s", checksum, size, path)); + } + } + + return checksumList; + } + } +} diff --git a/src/main/java/com/midm/service/device/ProfileAdvisor.java b/src/main/java/com/midm/service/device/ProfileAdvisor.java new file mode 100644 index 0000000..21d5140 --- /dev/null +++ b/src/main/java/com/midm/service/device/ProfileAdvisor.java @@ -0,0 +1,575 @@ +package com.midm.service.device; + +import com.google.common.base.Strings; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.ProfileApps; +import com.midm.model.file.AppFile; +import com.midm.model.file.BaseFile; +import com.midm.model.file.OtaFile; +import com.midm.service.BaseService; +import com.midm.service.file.FileService; +import com.mitac.cell.db.DbObject; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class ProfileAdvisor extends BaseService { + @Autowired + private DeviceService deviceService; + @Autowired + private ProfileService profileService; + @Autowired + private FileService fileService; + + public Document advice(UUID uuid) { + Set groupUuids = new HashSet(); + DeviceProfile profile = this.profileService.find(uuid, false); + if (profile != null) { + Set deviceGroupUuids = profile.getScopedDeviceGroups(); + if (deviceGroupUuids != null && !deviceGroupUuids.isEmpty()) { + for(UUID deviceGroupUuid : deviceGroupUuids) { + groupUuids.add(deviceGroupUuid); + List groups = this.deviceService.findChildGroups(deviceGroupUuid); + groups.forEach((group) -> groupUuids.add(group.getUuid())); + } + } + } + + Criteria critiera = (new Criteria()).orOperator(new Criteria[]{Criteria.where("isGlobal").is(true), Criteria.where("scope.group").in(groupUuids)}); + List profiles = this.mongoTemplate.find(Query.query(critiera), DeviceProfile.class); + return this.advice(profiles); + } + + public Document advice(List profiles) { + DbObject conflicts = new DbObject(); + Document settings = this.getConflictSettings(profiles); + Document apps = this.getConflictApps(profiles); + Document otas = this.getOtaAdvice(profiles); + Document files = this.getConflictFiles(profiles); + DbObject profilesObj = conflicts.getDbObject(new String[]{"profiles"}); + profiles.forEach((profile) -> profilesObj.append(profile.getUuid().toString(), profile.getName())); + if (settings != null && !settings.isEmpty()) { + conflicts.append("settings", settings); + } + + if (apps != null && !apps.isEmpty()) { + conflicts.append("apps", apps); + } + + if (otas != null && !otas.isEmpty()) { + conflicts.append("otas", otas); + } + + if (files != null && !files.isEmpty()) { + conflicts.append("files", files); + } + + return conflicts; + } + + private Document getConflictSettings(List profiles) { + if (profiles != null && profiles.size() >= 2) { + DbObject configs = new DbObject(); + String[] customSettingsCategories = new String[]{"system", "systemProperties", "globalSettings", "systemSettings", "secureSettings", "network"}; + + for(DeviceProfile profile : profiles) { + String profileUuidStr = profile.getUuid().toString(); + + for(String category : customSettingsCategories) { + DbObject settings = profile.getSettingsCategory(new String[]{category}); + if (settings != null && !settings.isEmpty()) { + DbObject categorySettings = configs.getDbObject(new String[]{category}); + + for(Map.Entry entry : settings.entrySet()) { + String key = (String)entry.getKey(); + DbObject itemSettings = categorySettings.getDbObject(new String[]{key}); + DbObject settingsObj = itemSettings.getDbObject(new String[]{"settings"}); + Object setting = entry.getValue(); + settingsObj.append(profileUuidStr, setting); + } + } + } + } + + String[] otherSettingsCategories = new String[]{"developer", "security", "launcher", "settings", "midm", "otas"}; + + for(DeviceProfile profile : profiles) { + String profileUuidStr = profile.getUuid().toString(); + + for(String category : otherSettingsCategories) { + DbObject settings = profile.getSettingsCategory(new String[]{category}); + if (settings != null && !settings.isEmpty()) { + DbObject categorySettings = configs.getDbObject(new String[]{category}); + DbObject settingsObj = categorySettings.getDbObject(new String[]{"settings"}); + settingsObj.append(profileUuidStr, settings); + } + } + } + + Iterator> configIt = configs.entrySet().iterator(); + + while(configIt.hasNext()) { + Map.Entry entry = (Map.Entry)configIt.next(); + DbObject categorySettings = (DbObject)entry.getValue(); + if (categorySettings.isEmpty()) { + configIt.remove(); + } + + if (categorySettings.containsKey("settings")) { + if (categorySettings.getDbObject(new String[]{"settings"}).keySet().size() < 2) { + configIt.remove(); + } + } else { + Iterator> settingIt = categorySettings.entrySet().iterator(); + + while(settingIt.hasNext()) { + Map.Entry settingEntry = (Map.Entry)settingIt.next(); + DbObject settings = (DbObject)settingEntry.getValue(); + if (settings.getDbObject(new String[]{"settings"}).keySet().size() < 2) { + settingIt.remove(); + } + } + + if (categorySettings.keySet().isEmpty()) { + configIt.remove(); + } + } + } + + return configs; + } else { + return null; + } + } + + private Document getConflictApps(List profiles) { + if (profiles != null && profiles.size() >= 2) { + DbObject apps = new DbObject(); + Set installPackages = new HashSet(); + DbObject install = apps.getDbObject(new String[]{"install"}); + + for(DeviceProfile profile : profiles) { + profile.initApps(); + String uuid = profile.getUuid().toString(); + ProfileApps profileApps = profile.getApps(); + if (profileApps != null) { + List installApps = profileApps.getInstallApp(); + if (installApps != null) { + installApps.forEach((installApp) -> { + UUID appUuid = installApp.getUuid(); + AppFile appFile = this.fileService.findApp(appUuid, false); + if (appFile != null) { + String packageName = appFile.getPackageName(); + installPackages.add(packageName); + DbObject appObj = install.getDbObject(new String[]{appFile.getPackageName()}); + appObj.put("label", appFile.getLabel()); + List uuids = appObj.getList("profiles", String.class); + if (uuids == null) { + uuids = new ArrayList(); + appObj.put("profiles", uuids); + } + + uuids.add(uuid); + DbObject appSetting = install.getDbObject(new String[]{appFile.getPackageName(), "settings"}); + appSetting.getDbObject(new String[]{"grantAll"}).append(uuid, installApp.getGrantAll()); + appSetting.getDbObject(new String[]{"rebootOnUpdate"}).append(uuid, installApp.getRebootsOnUpdate()); + appSetting.getDbObject(new String[]{"silentInstall"}).append(uuid, installApp.getSilentInstall()); + appSetting.getDbObject(new String[]{"startsOnUpdate"}).append(uuid, installApp.getStartsOnUpdate()); + appSetting.getDbObject(new String[]{"versionCode"}).append(uuid, appFile.getVersionCode()); + appSetting.getDbObject(new String[]{"versionName"}).append(uuid, appFile.getVersionName()); + String certMd5 = appFile.getCertMd5(); + if (!Strings.isNullOrEmpty(certMd5)) { + appSetting.getDbObject(new String[]{"certMd5"}).append(uuid, certMd5); + } + + appSetting.getDbObject(new String[]{"checksum"}).append(uuid, appFile.getVersionCode()); + } + + }); + } + } + } + + Iterator> it = install.entrySet().iterator(); + + while(it.hasNext()) { + Map.Entry item = (Map.Entry)it.next(); + DbObject appObject = (DbObject)item.getValue(); + DbObject appSetting = appObject.getDbObject(new String[]{"settings"}); + boolean removeItem = appObject.getList("profiles", String.class).size() < 2; + if (removeItem) { + it.remove(); + } else { + for(Iterator> valueIt = appSetting.entrySet().iterator(); valueIt.hasNext(); appObject.remove("profiles")) { + Map.Entry valueItem = (Map.Entry)valueIt.next(); + DbObject settings = (DbObject)valueItem.getValue(); + Iterator> appIt = settings.entrySet().iterator(); + Object setting = null; + boolean remove = true; + + while(appIt.hasNext()) { + Map.Entry entry = (Map.Entry)appIt.next(); + if (setting == null) { + setting = entry.getValue(); + } else if (!setting.equals(entry.getValue())) { + remove = false; + break; + } + } + + if (remove) { + valueIt.remove(); + } + } + } + } + + if (install.isEmpty()) { + apps.remove("install"); + } + + String[] conflictCategories = new String[]{"uninstall", "disabled", "wifi_only", "black_list", "white_list"}; + + for(DeviceProfile profile : profiles) { + for(String category : conflictCategories) { + DbObject categoryApps = apps.getDbObject(new String[]{category}); + ProfileApps profileApps = profile.getApps(); + if (profileApps != null) { + List items; + switch (category) { + case "uninstall": + items = profileApps.getUninstall(); + break; + case "disabled": + items = profileApps.getDisabled(); + break; + case "wifi_only": + items = profileApps.getWifiOnly(); + break; + case "black_list": + items = profileApps.getBlackList(); + break; + case "white_list": + items = profileApps.getWhiteList(); + break; + default: + items = null; + } + + if (items != null && items.size() > 0) { + items.forEach((itemx) -> { + String packageName = itemx.getString("package"); + boolean forInstall = installPackages.contains(packageName); + DbObject appObj = categoryApps.getDbObject(new String[]{packageName, profile.getUuid().toString()}); + if (forInstall) { + switch (category) { + case "uninstall": + case "disabled": + case "black_list": + appObj.append("conflict", "install"); + } + } + + appObj.append("enable", itemx.getBoolean("enable", true)); + }); + } + } + } + } + + for(String category : conflictCategories) { + DbObject categoryApps = apps.getDbObject(new String[]{category}); + if (categoryApps != null) { + if (categoryApps.isEmpty()) { + apps.remove(category); + } else { + Iterator> categoryAppsIt = categoryApps.entrySet().iterator(); + + while(categoryAppsIt.hasNext()) { + Map.Entry appEntry = (Map.Entry)categoryAppsIt.next(); + DbObject appObj = (DbObject)appEntry.getValue(); + if (appObj != null && !appObj.isEmpty()) { + if (appObj.keySet().size() == 1) { + DbObject values = (DbObject)appObj.values().iterator().next(); + if (values.size() < 2) { + categoryAppsIt.remove(); + } + } + } else { + categoryAppsIt.remove(); + } + } + + if (categoryApps.isEmpty()) { + apps.remove(category); + } + } + } + } + + return apps; + } else { + return null; + } + } + + private Document getOtaAdvice(List profiles) { + if (profiles != null && !profiles.isEmpty()) { + DbObject otas = new DbObject(); + List otaFiles = new ArrayList(); + + for(DeviceProfile profile : profiles) { + List otaUuids = profile.getOtas(); + if (otaUuids != null && !otaUuids.isEmpty()) { + for(UUID otaUuid : otaUuids) { + String uuidStr = otaUuid.toString(); + OtaFile otaFile = this.fileService.findOta(otaUuid); + if (otaFile != null) { + boolean isSystemImage = otaFile.isSystemImage(); + DbObject typeObj = otas.getDbObject(new String[]{isSystemImage ? "base" : "region"}); + DbObject skuObj = typeObj.getDbObject(new String[]{isSystemImage ? otaFile.getSkuId() : otaFile.getCustomerId()}); + if (!isSystemImage) { + skuObj = skuObj.getDbObject(new String[]{otaFile.getDeviceId()}); + } + + DbObject otaObj = skuObj.getDbObject(new String[]{uuidStr}); + if (!otaObj.containsKey("fileName")) { + otaFiles.add(otaFile); + otaObj.append("fileName", otaFile.getFileName()); + otaObj.append("fileLength", otaFile.getLength()); + otaObj.append("product_id", otaFile.getProductId()); + otaObj.append("deviceId", otaFile.getDeviceId()); + otaObj.append("build_date", otaFile.getBuildDate()); + List compatibleSkus = otaFile.getCompatibleSkuIds(); + if (compatibleSkus != null && !compatibleSkus.isEmpty()) { + otaObj.append("compatibleSkus", compatibleSkus); + } + + if (otaFile.isPartial()) { + otaObj.append("preDisplayId", otaFile.getPreDisplayId()); + otaObj.append("preBuild", otaFile.getPreBuild()); + } + + if (otaFile.isSystemImage()) { + otaObj.append("display_id", otaFile.getDisplayId()); + } else { + otaObj.append("sku_id", otaFile.getSkuId()); + otaObj.append("release_version", otaFile.getReleaseVersion()); + otaObj.append("script_version", otaFile.getScriptVersion()); + } + } + + List profileUuids = otaObj.getList("profiles", UUID.class); + if (profileUuids == null) { + profileUuids = new ArrayList(); + otaObj.append("profiles", profileUuids); + } + + profileUuids.add(profile.getUuid()); + } + } + } + } + + Iterator> otasIt = otas.entrySet().iterator(); + + while(otasIt.hasNext()) { + Map.Entry rootEntry = (Map.Entry)otasIt.next(); + DbObject rootValue = (DbObject)rootEntry.getValue(); + String category = (String)rootEntry.getKey(); + if (category.equals("base")) { + Iterator> rootIt = rootValue.entrySet().iterator(); + + while(rootIt.hasNext()) { + Map.Entry skuEntry = (Map.Entry)rootIt.next(); + DbObject skuValue = (DbObject)skuEntry.getValue(); + if (skuValue.size() == 1) { + Map.Entry otaEntry = (Map.Entry)skuValue.entrySet().iterator().next(); + String otaUuid = (String)otaEntry.getKey(); + DbObject otaValue = (DbObject)otaEntry.getValue(); + List profileUuids = otaValue.getList("profiles", UUID.class); + if (profileUuids.size() < 2) { + skuValue.remove(otaUuid); + } + } + + if (skuValue.isEmpty()) { + rootIt.remove(); + } + } + } else { + Iterator> rootIt = rootValue.entrySet().iterator(); + + while(rootIt.hasNext()) { + Map.Entry skuEntry = (Map.Entry)rootIt.next(); + DbObject customerValue = (DbObject)skuEntry.getValue(); + Iterator> customerIt = customerValue.entrySet().iterator(); + + while(customerIt.hasNext()) { + Map.Entry customerEntry = (Map.Entry)customerIt.next(); + DbObject deviceValue = (DbObject)customerEntry.getValue(); + + for(Map.Entry deviceEntry : deviceValue.entrySet()) { + String otaUuid = (String)deviceEntry.getKey(); + DbObject otaValue = (DbObject)deviceEntry.getValue(); + List profileUuids = otaValue.getList("profiles", UUID.class); + if (profileUuids.size() < 2) { + deviceValue.remove(otaUuid); + } + } + + if (deviceValue.isEmpty()) { + customerIt.remove(); + } + } + + if (customerValue.isEmpty()) { + rootIt.remove(); + } + } + } + + if (rootValue.isEmpty()) { + otasIt.remove(); + } + } + + return otas; + } else { + return null; + } + } + + private Document getConflictFiles(List profiles) { + if (profiles != null && profiles.size() >= 2) { + DbObject files = new DbObject(); + DbObject push = new DbObject(); + DbObject move = new DbObject(); + DbObject delete = new DbObject(); + + for(DeviceProfile profile : profiles) { + String profileUuid = profile.getUuid().toString(); + DbObject fileSettings = profile.getFiles(); + if (fileSettings != null && !fileSettings.isEmpty()) { + List pushFiles = fileSettings.getList("push", DbObject.class); + if (pushFiles != null && !pushFiles.isEmpty()) { + for(DbObject pushFile : pushFiles) { + for(String uuid : pushFile.getList("sources", String.class)) { + BaseFile file = this.fileService.findFile(UUID.fromString(uuid)); + if (file != null) { + DbObject fileObj = push.getDbObject(new String[]{uuid}); + if (!fileObj.containsKey("fileName")) { + fileObj.append("fileName", file.getFileName()); + } + + if (!fileObj.containsKey("fileLength")) { + fileObj.append("fileLength", file.getLength()); + } + + DbObject destObj = fileObj.getDbObject(new String[]{"settings"}); + DbObject profileObj = new DbObject("dest", pushFile.getString("dest")); + if (pushFile.getBoolean("extract", false)) { + profileObj.append("extract", true); + } + + destObj.append(profileUuid, profileObj); + } + } + } + + List moveFiles = fileSettings.getList("move", DbObject.class); + if (moveFiles != null && !moveFiles.isEmpty()) { + for(DbObject moveFile : moveFiles) { + String path = moveFile.getString("path"); + DbObject itemObj = move.getDbObject(new String[]{path}); + DbObject profileObj = itemObj.getDbObject(new String[]{profileUuid}); + profileObj.append("dest", moveFile.getString("dest")); + if (moveFile.getBoolean("appendTimeStamp", false)) { + profileObj.append("appendTimeStamp", true); + } + } + + List deleteFiles = fileSettings.getList("delete", DbObject.class); + if (deleteFiles != null && !deleteFiles.isEmpty()) { + for(DbObject deleteFile : deleteFiles) { + String path = deleteFile.getString("path"); + List profileList = delete.getList(path, String.class); + if (profileList == null) { + profileList = new ArrayList(); + delete.append(path, profileList); + } + + profileList.add(profileUuid); + } + } + } + } + } + } + + if (!push.isEmpty()) { + Iterator> pushIt = push.entrySet().iterator(); + + while(pushIt.hasNext()) { + Map.Entry entry = (Map.Entry)pushIt.next(); + DbObject pushObj = (DbObject)entry.getValue(); + DbObject destObj = pushObj.getDbObject(new String[]{"settings"}); + if (destObj.size() < 2) { + pushIt.remove(); + } + } + + if (!push.isEmpty()) { + files.append("push", push); + } + } + + if (!move.isEmpty()) { + Iterator> deleteIt = delete.entrySet().iterator(); + + while(deleteIt.hasNext()) { + Map.Entry entry = (Map.Entry)deleteIt.next(); + List deleteObj = (List)entry.getValue(); + if (deleteObj.size() < 2) { + deleteIt.remove(); + } + } + + if (!delete.isEmpty()) { + files.append("delete", delete); + } + } + + if (!move.isEmpty()) { + Iterator> moveIt = move.entrySet().iterator(); + + while(moveIt.hasNext()) { + Map.Entry entry = (Map.Entry)moveIt.next(); + DbObject moveObj = (DbObject)entry.getValue(); + if (moveObj.size() < 2) { + moveIt.remove(); + } + } + + if (!move.isEmpty()) { + files.append("move", move); + } + } + + return files; + } else { + return null; + } + } +} diff --git a/src/main/java/com/midm/service/device/ProfileService.java b/src/main/java/com/midm/service/device/ProfileService.java new file mode 100644 index 0000000..dcd261e --- /dev/null +++ b/src/main/java/com/midm/service/device/ProfileService.java @@ -0,0 +1,1493 @@ +package com.midm.service.device; + +import com.google.common.base.Strings; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceApps; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.DeviceProfileGroup; +import com.midm.model.device.DeviceProfileState; +import com.midm.model.device.ProfileApps; +import com.midm.model.device.ProfileScope; +import com.midm.model.file.AppFile; +import com.midm.model.file.BaseFile; +import com.midm.model.file.OtaFile; +import com.midm.model.message.MidmPacket; +import com.midm.model.message.MidmQuery; +import com.midm.model.org.User; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.file.FileService; +import com.midm.service.log.LogService; +import com.midm.service.message.MidmWebSocketSession; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.UserService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import org.apache.commons.collections4.MapUtils; +import org.bson.Document; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.AddFieldsOperation; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.aggregation.LimitOperation; +import org.springframework.data.mongodb.core.aggregation.MatchOperation; +import org.springframework.data.mongodb.core.aggregation.ProjectionOperation; +import org.springframework.data.mongodb.core.aggregation.SkipOperation; +import org.springframework.data.mongodb.core.aggregation.SortOperation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +@Service +public class ProfileService extends BaseService { + @Autowired + @Lazy + private UserService userService; + @Autowired + @Lazy + private DeviceService deviceService; + @Autowired + @Lazy + private DeviceReportService reportService; + @Autowired + @Lazy + @Qualifier("fileService") + private FileService fileService; + @Autowired + @Lazy + private WebSocketSessionManager sessionManager; + @Autowired + private LogService logService; + private Map profiles = new HashMap(); + + public boolean exists(DeviceProfile profile) { + return this.exists(profile.getUuid()); + } + + public boolean exists(UUID profileUuid) { + return this.existsById(DeviceProfile.class, profileUuid); + } + + public DeviceProfile save(DeviceProfile profile) { + if (profile.isGlobal()) { + profile.setScope((ProfileScope)null); + } + + if (!profile.getProfile().containsKey("startsOn")) { + String startsOn = (new SimpleDateFormat("yyyy-MM-dd")).format(profile.getUpdated()); + profile.setProfile("startsOn", startsOn); + } + + profile.initApps(); + this.removeNonExistingFiles(profile, (Device)null); + profile = (DeviceProfile)this.saveDocument(profile); + UUID profileUuid = profile.getUuid(); + this.reportService.resetProfile(profileUuid); + if (this.profiles.containsKey(profileUuid)) { + this.profiles.remove(profileUuid); + } + + return profile; + } + + public UpdateResult enable(DeviceProfile profile, boolean enable) { + if (profile == null) { + return null; + } else { + Update update = Update.update("enabled", enable); + UpdateResult result = this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class); + if (!enable) { + this.profiles.remove(profile.getUuid()); + } + + return result; + } + } + + public void enable(UUID siteUuid, List profileUuids, boolean enabled) { + if (siteUuid != null && profileUuids != null && !profileUuids.isEmpty()) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("_id").in(profileUuids).and("enabled").is(!enabled)); + List deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class); + Update update = Update.update("enabled", enabled); + this.mongoTemplate.updateMulti(query, update, DeviceProfile.class); + if (!enabled) { + deviceProfiles.forEach((profile) -> { + UUID profileUuid = profile.getUuid(); + this.profiles.remove(profileUuid); + this.deleteProfileStateByProfile(profileUuid); + this.unsetSequence(profileUuid); + this.notifyDevicesToRemoveProfile(this.getScopedDevices(profile), profileUuid); + }); + } + + } + } + + public DeviceProfile find(UUID profileUuid, boolean minified) { + if (minified && this.profiles.containsKey(profileUuid)) { + return ((DeviceProfile)this.profiles.get(profileUuid)).clone(); + } else { + Query query = Query.query(Criteria.where("_id").is(profileUuid)); + if (minified) { + query.fields().exclude("created").exclude("deviceProfileGroup").exclude("writerUuid").exclude("siteUuid"); + } + + DeviceProfile profile = (DeviceProfile)this.mongoTemplate.findOne(query, DeviceProfile.class); + if (profile != null) { + profile.initApps(); + if (minified) { + this.profiles.put(profileUuid, profile.clone()); + } else { + User user = this.userService.findUserProfileByUserUuid(profile.getWriterUuid()); + profile.setWriter(user); + } + } + + return profile; + } + } + + public long count() { + return this.count(DeviceProfile.class); + } + + public List findAll() { + return this.findAll(DeviceProfile.class); + } + + public UpdateResult setSequence(List sequenceUuids) { + Query query = Query.query(Criteria.where("_id").in(sequenceUuids)); + Update update = new Update(); + update.set("sequence", sequenceUuids); + return this.mongoTemplate.updateMulti(query, update, DeviceProfile.class); + } + + public UpdateResult unsetSequence(UUID uuid) { + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(uuid)), (new Update()).unset("sequence"), DeviceProfile.class); + this.mongoTemplate.updateMulti(new Query(), (new Update()).pull("sequence", uuid), DeviceProfile.class); + return this.mongoTemplate.updateFirst(Query.query(Criteria.where("sequence").exists(true).and("sequence.1").exists(false)), (new Update()).unset("sequence"), DeviceProfile.class); + } + + public UpdateResult removeSequence(List sequenceUuids) { + Query query = Query.query(Criteria.where("_id").in(sequenceUuids)); + return this.mongoTemplate.updateMulti(query, (new Update()).unset("sequence"), DeviceProfile.class); + } + + public List findAllByDevice(Device device, boolean withRef, Boolean minified, boolean forApply) { + List deviceCriteria = new ArrayList(); + deviceCriteria.add(Criteria.where("isGlobal").is(true)); + if (device.getSerialNo() != null) { + deviceCriteria.add(Criteria.where("scope.device").is(device.getSerialNo())); + } + + List groups = this.deviceService.getDeviceGroupTree(device.getDeviceGroup()); + if (groups != null && !groups.isEmpty()) { + groups.forEach((group) -> deviceCriteria.add(Criteria.where("scope.group").is(group.getUuid()))); + } + + List periodCriteria = new ArrayList(); + periodCriteria.add((new Criteria()).orOperator(new Criteria[]{Criteria.where("profile.endsOption").is("never"), Criteria.where("profile.endsOption").exists(false)})); + String endDate = McDateTimeUtils.toString(DateTime.now(), "yyyy-MM-dd"); + periodCriteria.add(Criteria.where("profile.endsOption").ne("never").and("profile.ends").gt(endDate)); + Criteria criteria = (new Criteria()).andOperator(new Criteria[]{Criteria.where("siteUuid").is(device.getSiteUuid()), Criteria.where("enabled").is(true), (new Criteria()).orOperator(deviceCriteria), (new Criteria()).orOperator(periodCriteria)}); + Query query = Query.query(criteria); + if (minified) { + query.fields().exclude("created").exclude("deviceProfileGroup").exclude("scope").exclude("writerUuid").exclude("siteUuid"); + } + + List profiles = this.mongoTemplate.find(query, DeviceProfile.class); + if (!forApply) { + return profiles; + } else if (withRef) { + Iterator itProfiles = profiles.iterator(); + + while(itProfiles.hasNext()) { + this.updateReference((DeviceProfile)itProfiles.next(), device); + } + + return profiles; + } else { + Iterator itProfiles = profiles.iterator(); + + Set profileUuidsToRemove; + DeviceProfile profile; + for(profileUuidsToRemove = new HashSet(); itProfiles.hasNext(); profile.setSequence((List)null)) { + profile = (DeviceProfile)itProfiles.next(); + if (profile.hasSequence()) { + List sequencedUuids = profile.getSequence(); + this.removeToBeApplied(device, profile.getUuid(), sequencedUuids); + if (!sequencedUuids.isEmpty()) { + profileUuidsToRemove.addAll(sequencedUuids); + } + } + } + + itProfiles = profiles.iterator(); + + while(itProfiles.hasNext()) { + profile = (DeviceProfile)itProfiles.next(); + if (profileUuidsToRemove.contains(profile.getUuid())) { + itProfiles.remove(); + } else { + profile.initApps(); + this.removeNonExistingFiles(profile, device); + this.excludeOrdered(device, profile, true); + profile.convertCustomSettingsForDevice(); + if (device.hasOldClient() && !this.deviceService.newClientAppInstalled(device.getUuid())) { + profile.needOldFormat(); + DbObject profileObj = profile.getProfile(); + if (!profileObj.containsKey("repeatPeriod")) { + profile.setProfile("repeatPeriod", "none"); + } + } else if (device.getClientVersion() == 1135) { + List installUuids = profile.getInstallUuids(); + if (installUuids != null && !installUuids.isEmpty()) { + DeviceApps deviceApps = this.deviceService.getApps(device.getUuid()); + AppFile appToInstall = null; + + for(UUID appUuid : installUuids) { + AppFile appFile = this.fileService.findApp(appUuid, false); + long versionCode = appFile.getVersionCode(); + String packageName = appFile.getPackageName(); + if (!deviceApps.isAppInstalled(device.getSdkVersion(), packageName, versionCode, appFile.getMinSdkVersion())) { + if (packageName.equals("com.mitac.midm.client")) { + appToInstall = appFile; + break; + } + + if (appToInstall == null) { + appToInstall = appFile; + } + } + } + + if (appToInstall == null) { + profile.getApps().setInstall((List)null); + } else { + UUID fileUuid = appToInstall.getFileUuid(); + List installApps = profile.getInstallApps(); + if (installApps != null) { + Iterator itInstallApps = installApps.iterator(); + + while(itInstallApps.hasNext()) { + if (!((ProfileApps.InstallApp)itInstallApps.next()).getUuid().equals(fileUuid)) { + itInstallApps.remove(); + } + } + } + } + } + } + + if (this.deviceService.hasDateTimeProblem((long)device.getClientVersion())) { + profile.unsetDateTimeSettings(); + } + } + } + + return profiles; + } + } + + private void removeToBeApplied(Device device, UUID curUuid, List uuids) { + Iterator it = uuids.iterator(); + boolean found = false; + + while(it.hasNext()) { + UUID profileUuid = (UUID)it.next(); + it.remove(); + if (!found) { + if (profileUuid.equals(curUuid)) { + if (!this.isProfileApplied(profileUuid, device)) { + break; + } + + found = true; + } + } else if (!this.isProfileApplied(profileUuid, device)) { + break; + } + } + + } + + public boolean isProfileApplied(UUID profileUuid, Device device) { + DeviceProfile profile = this.find(profileUuid, true); + boolean isProfileApplied = this.reportService.isProfileApplied(device.getUuid(), profile); + if (isProfileApplied) { + return true; + } else { + return this.isAllOtasInstalled(profile, device) && this.isAllAppsInstalled(profile, device); + } + } + + public List profileStatesByDevice(Device device) { + UUID deviceUuid = device.getUuid(); + Criteria criteria = Criteria.where("siteUuid").is(device.getSiteUuid()).and("enabled").is(true); + List deviceCriteria = new ArrayList(); + deviceCriteria.add(Criteria.where("isGlobal").is(true)); + if (device.getSerialNo() != null) { + deviceCriteria.add(Criteria.where("scope.device").is(device.getSerialNo())); + } + + DeviceGroup deviceGroup = device.getDeviceGroup(); + if (deviceGroup != null) { + Set uuids = new HashSet(); + List parentGroups = this.deviceService.getDeviceGroupTree(deviceGroup); + if (parentGroups != null && !parentGroups.isEmpty()) { + parentGroups.forEach((group) -> uuids.add(group.getUuid())); + } + + if (!uuids.isEmpty()) { + deviceCriteria.add(Criteria.where("scope.group").in(uuids)); + } + } + + criteria.orOperator(deviceCriteria); + this.findAllByDeviceGroup(device.getGroupUuid()); + MatchOperation scopeMatchOp = new MatchOperation(criteria); + AggregationOperation projectOp = Aggregations.newOperation("{$project: {'name': '$profile.name', updated: {$toLong: '$updated'}}}"); + AddFieldsOperation addFieldOp = new AddFieldsOperation("deviceUuid", deviceUuid); + AggregationOperation lookupOp = Aggregations.newOperation(new Document("$lookup", (new Document("from", "deviceProfileState")).append("let", (new Document("profileUuid", "$_id")).append("deviceUuid", "$deviceUuid").append("updated", new Document("$toLong", "$updated"))).append("pipeline", Arrays.asList(new Document("$match", new Document("$expr", new Document("$and", Arrays.asList(new Document("$eq", Arrays.asList("$_id.profileUuid", "$$profileUuid")), new Document("$eq", Arrays.asList("$_id.deviceUuid", "$$deviceUuid")), new Document("$eq", Arrays.asList("$updated", "$$updated")))))), new Document("$project", (new Document("_id", 0)).append("updated", 0).append("_class", 0)))).append("as", "state"))); + AggregationOperation finalProjectOp = Aggregations.newOperation("{$project: {name: 1, updated: 1, state: {$first: '$state'}}}"); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{scopeMatchOp, projectOp, addFieldOp, lookupOp, finalProjectOp}); + List profiles = this.mongoTemplate.aggregate(aggregation, DeviceProfile.class, Document.class).getMappedResults(); + profiles.forEach((profile) -> { + if (profile.containsKey("state")) { + Document state = (Document)profile.get("state", Document.class); + String stateVal = state.getString("state"); + if (stateVal == null || stateVal.equals("in_progress")) { + UUID profileUuid = (UUID)profile.get("_id"); + DeviceProfile deviceProfile = this.find(profileUuid, true); + boolean isAllAppsInstalled = this.isAllAppsInstalled(deviceProfile, device); + boolean isAllOtasInstalled = this.isAllOtasInstalled(deviceProfile, device); + if (isAllAppsInstalled && isAllOtasInstalled) { + state.put("state", "done"); + this.reportService.updateProfileState(profileUuid, deviceUuid, "done"); + } else if (this.sessionManager.isOnline(deviceUuid)) { + if (!isAllAppsInstalled) { + this.sessionManager.updateInstalledApps(deviceUuid, 5); + } + + if (!isAllOtasInstalled) { + this.sessionManager.queryDeviceInfo(deviceUuid, (MidmWebSocketSession)null); + } + } + } + } + + }); + return profiles; + } + + private void removeNonExistingFiles(DeviceProfile profile, Device device) { + this.removeNonExistingApps(profile, device); + this.removeNonExistingOtas(profile); + this.removeNonExistingEtcFiles(profile); + } + + private void removeNonExistingOtas(DeviceProfile profile) { + List otas = profile.getOtas(); + if (otas != null && !otas.isEmpty()) { + Iterator it = otas.iterator(); + + while(it.hasNext()) { + UUID uuid = (UUID)it.next(); + BaseFile file = this.fileService.findOta(uuid); + if (file == null) { + it.remove(); + } + } + + if (otas.isEmpty()) { + profile.setOtas((List)null); + } + } + + } + + private void removeNonExistingApps(DeviceProfile profile, Device device) { + List installUuids = profile.getInstallUuids(); + if (installUuids != null && !installUuids.isEmpty()) { + Collection appFiles = this.fileService.findApps(profile.getInstallUuids(), (String)null, device == null ? Integer.MAX_VALUE : device.getSdkVersion()); + if (appFiles != null && !appFiles.isEmpty()) { + ProfileApps apps = profile.getApps(); + if (apps != null) { + Map installAppsMap = new HashMap(); + MapUtils.populateMap(installAppsMap, appFiles, BaseFile::getFileUuid); + long clientVersion = device == null ? -1L : (long)device.getClientVersion(); + boolean isOldClient = device != null && (clientVersion < 220L || clientVersion >= 1000L && clientVersion < 1100L); + ProfileApps.InstallApp clientApp = null; + ProfileApps.InstallApp systemApp = null; + DeviceApps deviceApps = device == null ? null : this.deviceService.getApps(device.getUuid()); + List appsToInstall = apps.getInstallApp(); + Iterator it = appsToInstall.iterator(); + + while(it.hasNext()) { + ProfileApps.InstallApp app = (ProfileApps.InstallApp)it.next(); + UUID uuid = app.getUuid(); + if (!installAppsMap.containsKey(uuid)) { + it.remove(); + } else if (isOldClient) { + AppFile appFile = (AppFile)installAppsMap.get(uuid); + String packageName = appFile.getPackageName(); + long versionCode = appFile.getVersionCode(); + if (packageName.equals("com.mitac.midm.client")) { + if (deviceApps == null || !deviceApps.isAppInstalled(device.getSdkVersion(), packageName, versionCode, appFile.getMinSdkVersion())) { + clientApp = app; + } + } else if (packageName.equals("com.mitac.midm.system") && (deviceApps == null || !deviceApps.isAppInstalled(device.getSdkVersion(), packageName, versionCode, appFile.getMinSdkVersion()))) { + systemApp = app; + } + } + } + + if (device != null && isOldClient) { + ProfileApps.InstallApp exceptApp = device.getSdkVersion() > 25 ? clientApp : systemApp; + if (exceptApp == null) { + exceptApp = device.getSdkVersion() > 25 ? systemApp : clientApp; + } + + if (exceptApp != null) { + profile.setUpdated(); + profile.setFiles((DbObject)null); + profile.setOtas((List)null); + it = appsToInstall.iterator(); + + while(it.hasNext()) { + ProfileApps.InstallApp app = (ProfileApps.InstallApp)it.next(); + if (app != exceptApp) { + it.remove(); + } + } + } + } + + if (appsToInstall.isEmpty()) { + apps.setInstall((List)null); + } else if (isOldClient) { + profile.setNeedOldFormat(true); + } + + if (apps.isEmpty()) { + profile.setApps((ProfileApps)null); + } + } + + } else { + profile.getApps().setInstall((List)null); + } + } + } + + private void removeNonExistingEtcFiles(DeviceProfile profile) { + DbObject files = profile.getFiles(); + if (files != null) { + List pushes = (List)files.get("push"); + if (pushes != null && !pushes.isEmpty()) { + for(Object push : pushes) { + List uuids = (List)((Map)push).get("sources"); + if (uuids != null && !uuids.isEmpty()) { + Iterator it = uuids.iterator(); + + while(it.hasNext()) { + Object value = it.next(); + UUID uuid = null; + if (value instanceof UUID) { + uuid = (UUID)value; + } else if (value instanceof String) { + try { + uuid = UUID.fromString((String)value); + } catch (Exception var11) { + } + } + + if (uuid != null) { + BaseFile file = this.fileService.findFile(uuid); + if (file == null) { + it.remove(); + } + } + } + } + } + } + + } + } + + public List findGroupFamily(UUID groupUuid) { + List groups = new ArrayList(); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("_id").is(groupUuid)), Aggregation.graphLookup("deviceProfileGroup").startWith(new String[]{"$_id"}).connectFrom("_id").connectTo("parentUuid").as("children")}); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceProfileGroup.class, DeviceProfileGroup.class); + DeviceProfileGroup group = (DeviceProfileGroup)results.getMappedResults().get(0); + List children = group.getChildren(); + if (children != null) { + group.setChildren((List)null); + groups.add(group); + groups.addAll(children); + } + + return groups; + } + + public List findGroupUUids(Collection groupUuids) { + List groups = new ArrayList(); + groupUuids.forEach((uuid) -> groups.addAll(this.findGroupFamily(uuid))); + return (List)groups.stream().map((groupElement) -> groupElement.getUuid()).collect(Collectors.toList()); + } + + public List findAllWithGroupPathAndAppliedQtyBySiteUuid(UUID siteUuid, List groupUuids) { + AggregationOperation profileStateLookupOp = Aggregations.newOperation("{$lookup: {from: 'deviceProfileState', let: {devices: '$devices', profileUuid:'$_id', updated: {$toLong: '$updated'}},pipeline: [{$match: {$expr: {$and: [{$eq: ['$_id.profileUuid', '$$profileUuid']}, {$eq:['$updated', '$$updated']}, {$in: ['$_id.deviceUuid', '$$devices._id']}, {$eq: ['$state', 'done']}]}}}, {$count: 'count'}],as: 'profile.appliedQty'}},"); + AggregationOperation qtyFieldOp = Aggregations.newOperation("{$addFields: {'profile.deviceQty':{$size:'$devices'}, 'profile.appliedQty': {$first: '$profile.appliedQty.count'}} }}"); + AggregationOperation projectHideDevicesOp = Aggregation.project(new String[0]).andExclude(new String[]{"devices"}); + Aggregation aggregationForGlobal = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("siteUuid").is(siteUuid).and("isGlobal").is(true)), Aggregation.sort(Direction.ASC, new String[]{"profile.name"}), Aggregations.newOperation(new Document("$lookup", (new Document("from", "device")).append("pipeline", Arrays.asList(new Document("$match", new Document("siteUuid", siteUuid)), new Document("$project", new Document("_id", 1)))).append("as", "devices"))), profileStateLookupOp, qtyFieldOp, projectHideDevicesOp}); + List profiles = new ArrayList(this.mongoTemplate.aggregate(aggregationForGlobal, DeviceProfile.class, DeviceProfile.class).getMappedResults()); + List criterias = new ArrayList(); + criterias.add(Criteria.where("siteUuid").is(siteUuid).and("isGlobal").is(false)); + if (groupUuids != null) { + if (groupUuids.isEmpty()) { + criterias.add(Criteria.where("deviceProfileGroup").exists(false)); + } else { + criterias.add(Criteria.where("deviceProfileGroup.$id").in(this.findGroupUUids(groupUuids))); + } + } + + Aggregation aggregationForNonGlobal = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match((new Criteria()).andOperator(criterias)), Aggregations.newOperation("{$graphLookup: {from: 'deviceProfileGroup', startWith: '$deviceProfileGroup.$id', connectFromField: 'parentUuid', connectToField: '_id', depthField: 'depth', as: 'parents'}}"), Aggregations.newOperation("{$unwind: {path:'$parents',preserveNullAndEmptyArrays: true}}"), Aggregations.newOperation("{$sort: {'parents.depth':-1}}"), Aggregations.newOperation("{$group: {_id: '$_id', profileCopy: {'$first': '$$ROOT'}, path: {$push: '$parents.profile.name'}}}"), Aggregations.newOperation("{$addFields: {'profileCopy.profile.groupPath': {$reduce: { input: '$path', initialValue: '', in: {$concat: [ '$$value', {$cond: [{$eq: ['$$value', '']}, '', '/']}, '$$this']}}}}}"), Aggregations.newOperation("{$replaceRoot: {newRoot: {$mergeObjects: '$profileCopy'}}}"), Aggregations.newOperation("{$project: {parents:0}}"), Aggregations.newOperation("{$lookup: {from: 'deviceGroup', let: {'scopeUuids': {$ifNull:['$scope.group', [] ]} },pipeline: [{$match: {$expr: {$in: ['$_id', '$$scopeUuids']} }}, {$project: {_id:0, 'profile.name': 1}}],as: 'profile.scopeGroupNames'}}"), Aggregations.newOperation("{$addFields: {'profile.scopeGroupNames': '$profile.scopeGroupNames.profile.name'}}"), Aggregations.newOperation("{$graphLookup: {from: 'deviceGroup', startWith: '$scope.group', connectFromField: '_id',connectToField: 'parentUuid', depthField: 'depth', as: 'childGroup'}}"), Aggregations.newOperation("{$lookup: {from: 'device', let: {childGroup: '$childGroup', selfGroups: {$ifNull:['$scope.group', [] ]}}, pipeline: [ {$match: {$expr: {$or: [{$in: ['$deviceGroup.$id', '$$childGroup._id']}, {$in: ['$deviceGroup.$id', '$$selfGroups']}] }}},{$project: {_id: 1}}], as: 'devices'}}"), Aggregations.newOperation("{$project: {childGroup: 0}}"), profileStateLookupOp, qtyFieldOp, projectHideDevicesOp, Aggregations.newOperation("{$sort: {'profile.groupPath': 1, 'profile.name': 1}}")}).withOptions(Aggregation.newAggregationOptions().collation(LocaleConst.COLLATION_DEFAULT).build()); + List nonGlobalProfiles = this.mongoTemplate.aggregate(aggregationForNonGlobal, DeviceProfile.class, DeviceProfile.class).getMappedResults(); + profiles.addAll(nonGlobalProfiles); + return profiles; + } + + public List findAllByDeviceGroup(UUID groupUuid) { + List profiles = new ArrayList(); + if (groupUuid == null) { + return profiles; + } else { + DeviceGroup group = (DeviceGroup)this.findById(DeviceGroup.class, groupUuid); + if (group == null) { + return profiles; + } else { + JsonObject jFilter = new JsonObject(); + jFilter.addProperty("scope.group", groupUuid.toString()); + profiles = this.find(DeviceProfile.class, jFilter, (String)null, (Sort.Direction)null); + if (group.getParentUuid() != null) { + profiles.addAll(0, this.findAllByDeviceGroup(group.getParentUuid())); + } + + return profiles; + } + } + } + + public DeviceProfile findByDeviceAndProfile(UUID deviceUuid, UUID profileUuid, boolean withRef, boolean minified) { + DeviceProfile deviceProfile = this.find(profileUuid, minified); + if (deviceUuid != null && deviceProfile != null) { + if (deviceProfile.getEnabled() && !deviceProfile.isEnded()) { + if (deviceProfile.isGlobal()) { + return deviceProfile; + } else if (!deviceProfile.hasScope()) { + return null; + } else { + Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid); + if (device != null) { + if (this.isGroupScoped(device.getDeviceGroup(), deviceProfile)) { + deviceProfile.convertCustomSettingsForDevice(); + if (withRef) { + this.updateReference(deviceProfile, device); + } else { + this.excludeOrdered(device, deviceProfile, minified); + } + } + + deviceProfile.setScope((ProfileScope)null); + return deviceProfile; + } else { + return null; + } + } + } else { + return null; + } + } else { + return deviceProfile; + } + } + + private void excludeOrdered(Device device, DeviceProfile deviceProfile, boolean minified) { + String order = deviceProfile.applyOrder(); + if (!order.equals("none")) { + DeviceProfileState prevState = this.reportService.getProfileState(device.getUuid(), deviceProfile); + if (prevState != null) { + if (prevState.isApplyFirstDone() || prevState.isDone()) { + return; + } + } else { + prevState = new DeviceProfileState(device, deviceProfile); + } + + DbObject settings = deviceProfile.getSettings(); + Object midmSettings = settings.get("midm"); + Object launcherSettings = settings.get("launcher"); + Object otaSettings = settings.get("otas"); + boolean statesUpdated = false; + boolean hasOrdered = false; + switch (order) { + case "settings": + deviceProfile.setApps((ProfileApps)null); + deviceProfile.setOtas((List)null); + deviceProfile.setFiles((DbObject)null); + hasOrdered = true; + break; + case "apps": + boolean isAppsInstalled = this.isAllAppsInstalled(deviceProfile, device); + if (isAppsInstalled) { + prevState.setApplyFirstState("done"); + statesUpdated = true; + } else { + deviceProfile.setSettings((DbObject)null); + deviceProfile.setOtas((List)null); + deviceProfile.setFiles((DbObject)null); + hasOrdered = true; + } + break; + case "otas": + boolean isOtaApplied = this.isAllOtasInstalled(deviceProfile, device); + if (isOtaApplied) { + prevState.setApplyFirstState("done"); + statesUpdated = true; + } else { + deviceProfile.setSettings((DbObject)null); + deviceProfile.setApps((ProfileApps)null); + deviceProfile.setFiles((DbObject)null); + hasOrdered = true; + } + } + + if (statesUpdated) { + this.reportService.saveDocument(prevState); + } + + if (hasOrdered) { + Date tempUpdateDate = new Date(deviceProfile.getUpdated().getTime() - 1L); + deviceProfile.setUpdated(tempUpdateDate); + if (otaSettings != null) { + deviceProfile.setSetting("otas", otaSettings); + } + + if (midmSettings != null) { + deviceProfile.setSetting("midm", midmSettings); + } + + if (launcherSettings != null) { + deviceProfile.setSetting("launcher", launcherSettings); + } + } + + } + } + + public boolean isAllAppsInstalled(DeviceProfile deviceProfile, Device device) { + List installAppUuids = deviceProfile.getInstallUuids(); + if (installAppUuids != null && !installAppUuids.isEmpty()) { + DeviceApps appsFromDev = this.deviceService.getApps(device.getUuid()); + if (appsFromDev == null) { + return false; + } else { + for(UUID uuid : installAppUuids) { + AppFile app = this.fileService.findApp(uuid, false); + if (app != null && !appsFromDev.isAppInstalled(device.getSdkVersion(), app.getPackageName(), app.getVersionCode(), app.getMinSdkVersion())) { + return false; + } + } + + return true; + } + } else { + return true; + } + } + + public boolean isAllOtasInstalled(DeviceProfile deviceProfile, Device device) { + List otas = deviceProfile.getOtas(); + if (otas != null && !otas.isEmpty()) { + String curDeviceId = device.getDeviceId(); + String curSkuId = device.getSkuId(); + long curBuildDate = device.getBuildDate(); + String curCustomerId = device.getCustomerId(); + String curScriptVersion = device.getScriptVersion(); + long curRegionBuildDate = device.getRegionBuildDate(); + if (curDeviceId != null) { + for(UUID uuid : otas) { + OtaFile ota = this.fileService.findOta(uuid); + if (curDeviceId.equals(ota.getDeviceId())) { + if (ota.isRegionImage()) { + if (curScriptVersion != null && curCustomerId != null && ota.getCustomerId().equals(curCustomerId) && !ota.getScriptVersion().equals(curScriptVersion) && (!deviceProfile.checkBuildDate() || curRegionBuildDate < ota.getBuildDate())) { + return false; + } + } else if (ota.getDeviceId().equals(curDeviceId) && curBuildDate < ota.getBuildDate()) { + if (curSkuId == null) { + return false; + } + + if (curSkuId.equals(ota.getSkuId())) { + return false; + } + } + } + } + } + + return true; + } else { + return true; + } + } + + public boolean isDeviceScoped(Device device, DeviceProfile deviceProfile) { + if (deviceProfile.getEnabled() && !deviceProfile.isEnded()) { + if (deviceProfile.isGlobal()) { + return true; + } else if (!deviceProfile.hasScope()) { + return false; + } else { + DeviceGroup group = device.getDeviceGroup(); + if (group != null) { + Set groupUuids = this.deviceService.findDevieGroupUuids(deviceProfile.getScopedDeviceGroups()); + if (groupUuids.contains(group.getUuid())) { + return true; + } + } + + Set scopedDevices = deviceProfile.getScopedDevice(); + return scopedDevices != null && scopedDevices.contains(device.getSerialNo()); + } + } else { + return false; + } + } + + public boolean isGroupScoped(DeviceGroup deviceGroup, DeviceProfile deviceProfile) { + Set groupUuids = deviceProfile.getScopedDeviceGroups(); + if (groupUuids != null && !groupUuids.isEmpty()) { + for(DeviceGroup group : this.deviceService.getDeviceGroupTree(deviceGroup)) { + if (groupUuids.contains(group.getUuid())) { + return true; + } + } + } + + return false; + } + + public DeviceProfile findBySiteUuidAndProfileName(UUID siteUuid, String profileName) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("profile.name").is(profileName)); + return (DeviceProfile)this.mongoTemplate.findOne(query, DeviceProfile.class); + } + + public DeviceProfile findOne(User user) { + Query query = Query.query(Criteria.where("siteUuid").is(user.getSiteUuid())); + return (DeviceProfile)this.mongoTemplate.findOne(query, DeviceProfile.class); + } + + public List findAllByApp(UUID appUuid) { + Criteria criteria = (new Criteria()).orOperator(new Criteria[]{Criteria.where("apps.install").is(appUuid.toString()), Criteria.where("apps.install").is(appUuid), Criteria.where("apps.install").elemMatch(Criteria.where("uuid").is(appUuid.toString())), Criteria.where("apps.install").elemMatch(Criteria.where("uuid").is(appUuid))}); + Sort sort = Sort.by(Direction.DESC, new String[]{"isGlobal"}); + Query query = Query.query(criteria).with(sort); + List profiles = this.mongoTemplate.find(query, DeviceProfile.class); + return profiles; + } + + public List findAllByOta(UUID otaUuid) { + Criteria criteria = Criteria.where("otas").is(otaUuid); + Sort sort = Sort.by(Direction.DESC, new String[]{"isGlobal"}); + Query query = Query.query(criteria).with(sort); + List profiles = this.mongoTemplate.find(query, DeviceProfile.class); + return profiles; + } + + public List findAllByFile(UUID fileUuid) { + String uuidString = fileUuid.toString(); + Criteria criteria = new Criteria(); + criteria.orOperator(new Criteria[]{Criteria.where("files.push").elemMatch(Criteria.where("sources").is(uuidString)), Criteria.where("settings.system.display.wallpaper").is(uuidString)}); + Sort sort = Sort.by(Direction.DESC, new String[]{"isGlobal"}); + Query query = Query.query(criteria).with(sort); + List profiles = this.mongoTemplate.find(query, DeviceProfile.class); + return profiles; + } + + public Page findProfiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + Page resultPage = this.findByPage(DeviceProfile.class, filter, sortBy, direction, page, size); + + for(DeviceProfile profile : resultPage.getContent()) { + User user = (User)this.findById(User.class, profile.getWriterUuid()); + if (user != null) { + user.setPassword((String)null); + profile.setWriter(user); + } + } + + return resultPage; + } + + public List findProfiles(JsonObject filter, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + List profiles = this.find(DeviceProfile.class, filter, sortBy, direction); + return profiles; + } + + public Page findDevices(UUID profileUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + DeviceProfile profile = (DeviceProfile)this.findById(DeviceProfile.class, profileUuid); + if (profile == null) { + return Page.empty(); + } else { + Criteria criteria = Criteria.where("siteUuid").is(profile.getSiteUuid()); + MatchOperation profileStatesOp = null; + if (filter != null) { + for(String key : filter.keySet()) { + switch (key) { + case "siteUuid": + case "deviceGroups": + break; + case "states.profile.state": + String state = filter.get(key).getAsString(); + if (!Strings.isNullOrEmpty(state) && !state.equals("unknown")) { + profileStatesOp = new MatchOperation(Criteria.where(key).is(state)); + } else { + profileStatesOp = new MatchOperation(Criteria.where(key).exists(false)); + } + break; + default: + criteria.and(key).regex(McMongoUtils.escapedPattern(filter.get(key).getAsString())); + } + } + } + + if (filter != null && filter.has("deviceGroups")) { + Set groupUuids = new HashSet(); + JsonArray jGroups = filter.getAsJsonArray("deviceGroups"); + if (jGroups.isEmpty()) { + criteria.and("deviceGroup").exists(false); + } else { + for(JsonElement jGroup : jGroups) { + UUID groupUuid = UUID.fromString(jGroup.getAsString()); + List deviceGroups = this.deviceService.findGroupFamily(groupUuid); + deviceGroups.forEach((group) -> groupUuids.add(group.getUuid())); + } + + if (!groupUuids.isEmpty()) { + criteria.and("deviceGroup.$id").in(groupUuids); + } + } + } else if (!profile.isGlobal()) { + List scopeCriterias = new ArrayList(); + Set groupUuids = new HashSet(); + Set scopedGroups = profile.getScopedDeviceGroups(); + if (scopedGroups != null && !scopedGroups.isEmpty()) { + for(UUID groupUuid : scopedGroups) { + List deviceGroups = this.deviceService.findGroupFamily(groupUuid); + deviceGroups.forEach((group) -> groupUuids.add(group.getUuid())); + } + + if (groupUuids.isEmpty()) { + return new PageImpl(new ArrayList(), PageRequest.of(page, size), 0L); + } + + scopeCriterias.add(Criteria.where("deviceGroup.$id").in(groupUuids)); + } + + Set deviceSerials = profile.getScopedDevice(); + if (deviceSerials != null && !deviceSerials.isEmpty()) { + scopeCriterias.add(Criteria.where("profile.hardware_info.serial_no").in(deviceSerials)); + } + + if (!scopeCriterias.isEmpty()) { + criteria.orOperator(scopeCriterias); + } + } + + Query query = Query.query(criteria); + Long total = this.mongoTemplate.count(query, Device.class); + if (total == 0L) { + Pageable pageable = PageRequest.of(0, size); + return new PageImpl(new ArrayList(), pageable, total); + } else { + List operations = new ArrayList(); + MatchOperation matchOp = new MatchOperation(criteria); + operations.add(matchOp); + if (profile.getEnabled()) { + AggregationOperation lookupOp = Aggregations.newOperation(new Document("$lookup", (new Document("from", "deviceProfileState")).append("let", new Document("id", "$_id")).append("pipeline", Arrays.asList(new Document("$match", new Document("$expr", new Document("$and", Arrays.asList(new Document("$eq", Arrays.asList("$_id.deviceUuid", "$$id")), new Document("$eq", Arrays.asList("$_id.profileUuid", profile.getUuid())), new Document("$eq", Arrays.asList("$updated", profile.getUpdated().getTime())))))), new Document("$project", (new Document("_id", 0)).append("updated", 0).append("_class", 0)))).append("as", "profileState"))); + operations.add(lookupOp); + AggregationOperation addFieldsOp = Aggregations.newOperation(new Document("$addFields", new Document("states.profile", new Document("$first", "$profileState")))); + operations.add(addFieldsOp); + ProjectionOperation projectOp = (new ProjectionOperation()).andExclude(new String[]{"profileState"}); + operations.add(projectOp); + if (profileStatesOp != null) { + operations.add(profileStatesOp); + } + } + + SortOperation sortOp = new SortOperation(Sort.by(direction, new String[]{sortBy})); + operations.add(sortOp); + SkipOperation skipOp = new SkipOperation((long)(page * size)); + operations.add(skipOp); + LimitOperation limitOp = new LimitOperation((long)size); + operations.add(limitOp); + Aggregation aggregation = Aggregation.newAggregation(operations).withOptions(Aggregation.newAggregationOptions().collation(LocaleConst.COLLATION_DEFAULT).build()); + List devices = this.mongoTemplate.aggregate(aggregation, Device.class, Device.class).getMappedResults(); + devices.forEach((device) -> { + DbObject state = device.getStates().getDbObject(new String[]{"profile"}); + if (state.containsKey("state") && state.getString("state").equals("in_progress") && this.isProfileApplied(profileUuid, device)) { + state.put("state", "done"); + this.reportService.updateProfileState(profileUuid, device.getUuid(), "done"); + } + + }); + page = this.page(total, page, size); + Pageable pageable = PageRequest.of(page, size); + return new PageImpl(devices, pageable, total); + } + } + } + + public boolean updateScope(DeviceProfile profile, String command, Set devices, Set groups) { + Update update = new Update(); + if (command.equals("add")) { + if (groups != null && !groups.isEmpty()) { + update.addToSet("scope.group").each(new Object[]{groups}); + } + + if (devices != null && !devices.isEmpty()) { + update.addToSet("scope.device").each(new Object[]{devices}); + } + } else { + if (groups != null && !groups.isEmpty()) { + update.pullAll("scope.group", groups.toArray()); + } + + if (devices != null && !devices.isEmpty()) { + update.pullAll("scope.device", devices.toArray()); + } + } + + Query query = Query.query(Criteria.where("_id").is(profile.getUuid())); + boolean updated = this.mongoTemplate.updateFirst(query, update, DeviceProfile.class).getModifiedCount() > 0L; + if (updated) { + List allDevices = this.getScopedDevices(profile); + if (allDevices != null) { + allDevices.forEach((device) -> { + if (!this.reportService.isProfileApplied(device.getUuid(), profile)) { + this.notifyUpdate(device, profile, false); + } + + }); + } + } + + if (command.equals("remove")) { + this.removeIfNoScope(profile.getUuid()); + } + + this.profiles.remove(profile.getUuid()); + return updated; + } + + public void unscope(DeviceProfile profile, String serialNo) { + UUID profileUuid = profile.getUuid(); + Criteria criteria = Criteria.where("_id").is(profileUuid); + this.mongoTemplate.updateFirst(Query.query(criteria), (new Update()).pull("scope.device", serialNo), DeviceProfile.class); + this.removeIfNoScope(profileUuid); + } + + private void removeIfNoScope(UUID profileUuid) { + if (profileUuid != null) { + DeviceProfile profile = (DeviceProfile)this.findById(DeviceProfile.class, profileUuid); + if (profile.removeIfNoScope() && !profile.hasScope()) { + this.delete(profileUuid); + } + + this.profiles.remove(profileUuid); + } + } + + public void delete(DeviceProfile profile) { + this.delete(profile.getUuid()); + } + + public void delete(UUID profileUuid) { + this.logService.clearAllLogsFor(profileUuid); + this.deleteById(DeviceProfile.class, profileUuid); + this.deleteProfileStateByProfile(profileUuid); + this.unsetSequence(profileUuid); + this.profiles.remove(profileUuid); + } + + public void deleteProfileStateByProfile(UUID profileUuid) { + this.mongoTemplate.remove(Query.query(Criteria.where("_id.profileUuid").is(profileUuid)), DeviceProfileState.class); + } + + public boolean notifyToSync(UUID deviceUuid, UUID profileUuid, String request, int code) { + Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid); + return device != null && this.notifyToSync(device, profileUuid, request, code); + } + + public boolean notifyToSync(String serialNo, UUID profileUuid, String request, int code) { + Device device = this.deviceService.findBySerialNo(serialNo); + return device != null && this.notifyToSync(device, profileUuid, request, code); + } + + public boolean notifyToSync(Device device, UUID profileUuid, String request, int code) { + if (this.sessionManager.isOnline(device.getUuid())) { + MidmQuery query = new MidmQuery(); + query.setRequest(request); + query.setCode(code); + query.setParam("data", profileUuid); + MidmPacket packet = new MidmPacket(); + packet.setQuery(query); + packet.setRecieverUuid(device.getUuid()); + this.sessionManager.sendMessage(packet); + return true; + } else { + return false; + } + } + + public boolean notifyUpdate(Device device) { + return this.notifyUpdate(device.getUuid()); + } + + public boolean notifyUpdate(UUID deviceUuid) { + if (!this.sessionManager.isOnline(deviceUuid)) { + return true; + } else { + MidmQuery query = new MidmQuery(); + query.setRequest("update_profile_all"); + query.setCode(132); + MidmPacket packet = new MidmPacket(); + packet.setQuery(query); + packet.setRecieverUuid(deviceUuid); + this.sessionManager.sendMessage(packet); + return true; + } + } + + public List getScopedDevices(DeviceProfile deviceProfile) { + Criteria criteria = Criteria.where("siteUuid").is(deviceProfile.getSiteUuid()).and("enabled").is(true); + if (!deviceProfile.isGlobal()) { + Set groupUuids = deviceProfile.getScopedDeviceGroups(); + groupUuids = this.deviceService.findDevieGroupUuids(groupUuids); + List criterias = new ArrayList(); + if (groupUuids != null && !groupUuids.isEmpty()) { + criterias.add(Criteria.where("deviceGroup.$id").in(groupUuids)); + } + + Set serials = deviceProfile.getScopedDevice(); + if (serials != null && !serials.isEmpty()) { + criterias.add(Criteria.where("profile.hardware_info.serial_no").in(serials)); + } + + if (criterias.isEmpty()) { + return null; + } + + criteria.orOperator(criterias); + } + + return this.mongoTemplate.find(Query.query(criteria), Device.class); + } + + public void notifyUpdateAfter(UUID deviceUuid, UUID profileUuid, int secondAfter) { + Date schedule = DateTime.now().plusSeconds(secondAfter).toDate(); + this.schedule(() -> { + DeviceProfile deviceProfile = this.find(profileUuid, true); + Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid); + this.notifyUpdate(device, deviceProfile, false); + }, schedule); + } + + public boolean notifyUpdate(DeviceProfile profile, boolean forceToUpdate) { + if (profile != null && profile.getEnabled()) { + List devices = this.getScopedDevices(profile); + if (devices != null && !devices.isEmpty()) { + profile.convertCustomSettingsForDevice(); + + for(Device device : devices) { + this.notifyUpdate(device, profile, forceToUpdate); + } + + return true; + } else { + return false; + } + } else { + return true; + } + } + + @Async + public void notifyUpdate(Device device, DeviceProfile profile, boolean forceToUpdate) { + if (device != null && profile != null && this.sessionManager.isOnline(device.getUuid()) && profile.getEnabled()) { + if (forceToUpdate || !this.isProfileApplied(profile.getUuid(), device)) { + profile = profile.clone(); + this.excludeOrdered(device, profile, true); + this.removeNonExistingApps(profile, device); + MidmQuery query = new MidmQuery(); + query.setRequest("update_profile"); + query.setCode(131); + query.setParam("data", profile); + MidmPacket packet = new MidmPacket(); + packet.setQuery(query); + packet.setRecieverUuid(device.getUuid()); + this.sessionManager.sendMessage(packet); + } + } + } + + public boolean notifyUpdateAll(DeviceProfile deviceProfile) { + if (deviceProfile == null) { + return true; + } else if (!deviceProfile.getEnabled()) { + return true; + } else { + MidmQuery midmQuery = new MidmQuery(); + midmQuery.setRequest("update_profile_all"); + midmQuery.setCode(132); + MidmPacket packet = new MidmPacket(); + packet.setQuery(midmQuery); + List devices = null; + if (deviceProfile.isGlobal()) { + devices = this.deviceService.findDevicesBySiteUuid(deviceProfile.getSiteUuid()); + } else { + Set groupUuids = this.deviceService.findDevieGroupUuids(deviceProfile.getScopedDeviceGroups()); + if (groupUuids == null || groupUuids.isEmpty()) { + return false; + } + + Query query = Query.query(Criteria.where("deviceGroup.$id").in(groupUuids)); + devices = this.mongoTemplate.find(query, Device.class); + } + + if (devices != null && !devices.isEmpty()) { + for(Device device : devices) { + if (this.sessionManager.isOnline(device.getUuid())) { + packet.setRecieverUuid(device.getUuid()); + this.sessionManager.sendMessage(packet); + } + } + + return true; + } else { + return false; + } + } + } + + public DeviceProfileGroup save(DeviceProfileGroup group) { + if (group.getUuid() == null) { + group.init(); + } + + return (DeviceProfileGroup)this.saveDocument(group); + } + + public DeviceProfileGroup findDeviceProfileGroup(UUID groupUuid) { + return groupUuid == null ? null : (DeviceProfileGroup)this.findById(DeviceProfileGroup.class, groupUuid); + } + + public DeviceProfileGroup findDeviceProfileGroup(String path) { + if (McStringUtils.isNullOrEmpty(path)) { + return null; + } else { + String[] elements = path.split(Pattern.quote("/")); + DeviceProfileGroup parentGroup = null; + + for(int i = 0; i < elements.length; ++i) { + DeviceProfileGroup group = this.findDeviceProfileGroup(parentGroup, elements[i].trim()); + if (group == null) { + return null; + } + + parentGroup = group; + } + + return parentGroup; + } + } + + public List findDeviceProfileGroupByName(String name) { + String sortBy = "profile.name"; + Sort.Direction direction = Direction.ASC; + List groups = this.find(DeviceProfileGroup.class, this.getProfileFilter("name", name), "profile.name", direction); + return groups; + } + + public List findDeviceProfileGroupByParentGroup(UUID parentGroupUuid) { + Query query = Query.query(Criteria.where("parentUuid").is(parentGroupUuid)); + return this.mongoTemplate.find(query, DeviceProfileGroup.class); + } + + private DeviceProfileGroup findDeviceProfileGroup(DeviceProfileGroup parent, String childName) { + List groups = null; + if (parent == null) { + groups = this.findDeviceProfileGroupByName(childName); + } else { + groups = this.findDeviceProfileGroupByParentGroup(parent.getUuid()); + } + + for(DeviceProfileGroup group : groups) { + if ((parent != null || group.getParentUuid() == null) && group.getName().equals(childName)) { + return group; + } + } + + return null; + } + + public List findAllDeviceProfileGroups(UUID siteUuid) { + Sort sort = Sort.by(new String[]{"parentUuid"}).and(Sort.by(new String[]{"order"})).and(Sort.by(new String[]{"profile.name"})); + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + query.with(sort); + List groups = this.mongoTemplate.find(query, DeviceProfileGroup.class); + + for(DeviceProfileGroup group : groups) { + UUID groupUuid = group.getUuid(); + if (groupUuid != null) { + Long numbers = this.mongoTemplate.count(new Query(Criteria.where("deviceProfileGroup.$id").is(groupUuid)), DeviceProfile.class); + if (numbers != null) { + group.setDeviceProfileNumbers(numbers); + } + } + } + + return groups; + } + + public long getProfileCount(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.count(query, DeviceProfile.class); + } + + public void delete(DeviceProfileGroup group) { + if (group != null && group.getUuid() != null) { + for(DeviceProfileGroup childGroup : this.findDeviceProfileGroupByParentGroup(group.getUuid())) { + this.delete(childGroup); + } + + this.mongoTemplate.updateMulti(new Query(Criteria.where("deviceProfileGroup.$id").is(group.getUuid())), (new Update()).unset("deviceProfileGroup"), DeviceProfile.class); + this.deleteById(DeviceProfileGroup.class, group.getUuid()); + } + } + + private void updateReference(DeviceProfile profile, Device device) { + profile.initApps(); + List appUuids = profile.getInstallUuids(); + if (appUuids != null && !appUuids.isEmpty()) { + Collection apps = this.fileService.findApps(appUuids, (String)null, device.getSdkVersion()); + if (apps != null && !apps.isEmpty()) { + Map appMap = new HashMap(); + Map packageMap = new HashMap(); + apps.forEach((app) -> { + DbObject fileInfo = app.getFileInfo(); + fileInfo.put("info", app.getAppInfo()); + String packageName = app.getPackageName(); + if (app.getMinSdkVersion() <= device.getSdkVersion() && (!packageMap.containsKey(packageName) || ((AppFile)packageMap.get(packageName)).getVersionCode() >= app.getVersionCode())) { + packageMap.put(app.getPackageName(), app); + appMap.put(app.getFileUuid(), fileInfo); + } + + }); + profile.setReference("apps", appMap); + Iterator itInstallApps = profile.getInstallApps().iterator(); + + while(itInstallApps.hasNext()) { + if (!appMap.containsKey(((ProfileApps.InstallApp)itInstallApps.next()).getUuid())) { + itInstallApps.remove(); + } + } + } + } else { + profile.setReference("apps", (Object)null); + } + + List otaUuids = profile.getOtas(); + if (otaUuids != null && !otaUuids.isEmpty()) { + boolean partialFirst = profile.getSettingAsBoolean("otas", "partialFirst", true); + List otas = this.fileService.findOtas(otaUuids, device, profile.checkBuildDate(), partialFirst); + if (otas != null && !otas.isEmpty()) { + otaUuids.clear(); + Map otaMap = new HashMap(); + otas.forEach((ota) -> { + UUID fileUuid = ota.getFileUuid(); + otaUuids.add(fileUuid); + DbObject fileInfo = ota.getFileInfo(); + fileInfo.put("info", ota.getOtaInfo()); + otaMap.put(fileUuid, fileInfo); + }); + profile.setReference("otas", otaMap); + } else { + profile.setOtas((List)null); + } + } else { + profile.setOtas((List)null); + profile.setReference("otas", (Object)null); + } + + Set fileUuids = profile.getFileUUids(); + if (fileUuids != null && !fileUuids.isEmpty()) { + List files = this.fileService.findFiles(fileUuids); + if (files != null && !files.isEmpty()) { + Map fileMap = (Map)files.stream().collect(Collectors.toMap((file) -> file.getFileUuid(), (file) -> file.getFileInfo())); + profile.setReference("files", fileMap); + } + } else { + profile.setReference("files", (Object)null); + } + + } + + public String getGroupPath(DeviceProfileGroup group) { + String path = ""; + if (group != null) { + path = group.getProfile("name").toString(); + if (group.getParentUuid() != null) { + DeviceProfileGroup parent = (DeviceProfileGroup)this.findById(DeviceProfileGroup.class, group.getParentUuid()); + String var10000 = this.getGroupPath(parent); + path = var10000 + "/" + path; + } + } + + return path; + } + + public List findAllBySiteUuid(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.find(query, DeviceProfile.class); + } + + public List findAllGroupBySiteUuid(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.find(query, DeviceProfileGroup.class); + } + + public DeleteResult deleteProfileBySiteUuid(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.remove(query, DeviceProfile.class); + } + + public DeleteResult deleteProfileGroupBySiteUuid(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.remove(query, DeviceProfileGroup.class); + } + + public String getNewName(UUID siteUuid, String profileName) { + int number = 1; + + String newName; + for(newName = profileName; this.findBySiteUuidAndProfileName(siteUuid, newName) != null; newName = profileName + String.format(" (%d)", number++)) { + } + + return newName; + } + + public Document getProfileState(DeviceProfile profile) { + if (profile == null) { + return null; + } else { + Document resultDocument = (new Document("uuid", profile.getUuid())).append("name", profile.getName()); + UUID siteUuid = profile.getSiteUuid(); + Criteria criteria = Criteria.where("siteUuid").is(siteUuid); + if (!profile.isGlobal()) { + Set groupUuids = profile.getScopedDeviceGroups(); + List groupCriteria = new ArrayList(); + if (groupUuids != null && !groupUuids.isEmpty()) { + groupUuids.forEach((groupUuid) -> this.deviceService.findGroupFamily(groupUuid).forEach((group) -> groupCriteria.add(Criteria.where("deviceGroup.$id").is(group.getUuid())))); + } + + if (groupCriteria.isEmpty()) { + resultDocument.append("total", 0).append("success", 0).append("fail", 0); + return resultDocument; + } + + criteria.orOperator(groupCriteria); + } + + MatchOperation matchOp = new MatchOperation(criteria); + AggregationOperation lookupOp = Aggregations.newOperation(new Document("$lookup", (new Document("from", "deviceProfileState")).append("let", new Document("id", "$_id")).append("pipeline", Arrays.asList(new Document("$match", new Document("$expr", new Document("$and", Arrays.asList(new Document("$eq", Arrays.asList("$_id.deviceUuid", "$$id")), new Document("$eq", Arrays.asList("$_id.profileUuid", profile.getUuid())), new Document("$eq", Arrays.asList("$updated", profile.getUpdated().getTime())))))))).append("as", "report"))); + AggregationOperation groupOp = Aggregations.newOperation(new Document("$group", (new Document("_id", (Object)null)).append("total", new Document("$sum", 1)).append("success", new Document("$sum", new Document("$cond", Arrays.asList(new Document("$ne", Arrays.asList("$report", new ArrayList())), 1, 0)))).append("fail", new Document("$sum", new Document("$cond", Arrays.asList(new Document("$eq", Arrays.asList("$report", new ArrayList())), 1, 0)))))); + ProjectionOperation projectionOp = (new ProjectionOperation()).andExclude(new String[]{"_id"}); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{matchOp, lookupOp, groupOp, projectionOp}); + AggregationResults result = this.mongoTemplate.aggregate(aggregation, Device.class, Document.class); + List mappedResult = result.getMappedResults(); + if (mappedResult.isEmpty()) { + resultDocument.append("total", 0).append("success", 0).append("fail", 0); + } else { + resultDocument.putAll((Map)result.getMappedResults().get(0)); + } + + return resultDocument; + } + } + + public void notifyDevicesToRemoveProfile(Collection devices, UUID profileUuid) { + if (devices != null && !devices.isEmpty() && profileUuid != null) { + int code = 136; + String command = "remove_profile"; + if (devices != null && !devices.isEmpty()) { + for(Object device : devices) { + if (device instanceof UUID) { + this.notifyToSync((UUID)device, profileUuid, command, code); + } else if (device instanceof String) { + this.notifyToSync((String)device, profileUuid, command, code); + } else if (device instanceof Device) { + this.notifyToSync((Device)device, profileUuid, command, code); + } + } + } + + } + } +} diff --git a/src/main/java/com/midm/service/file/DeviceFilesService.java b/src/main/java/com/midm/service/file/DeviceFilesService.java new file mode 100644 index 0000000..39b9e5f --- /dev/null +++ b/src/main/java/com/midm/service/file/DeviceFilesService.java @@ -0,0 +1,141 @@ +package com.midm.service.file; + +import com.google.gson.JsonObject; +import com.midm.model.device.Device; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.Site; +import com.midm.model.org.SiteFile; +import com.midm.model.org.User; +import com.midm.service.EmailService; +import com.midm.service.news.NewsMessageService; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McStringUtils; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service("deviceFileService") +public class DeviceFilesService extends FileService { + @Autowired + private NewsMessageService newsMessageService; + @Autowired + private EmailService emailService; + + public void save(SiteFile file) { + this.saveDocument(file); + } + + public SiteFile findDeviceFileByUuid(UUID uuid) { + return (SiteFile)this.findById(SiteFile.class, uuid); + } + + public Page findDeviceFiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "requested"; + direction = Direction.DESC; + } + + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + query.addCriteria(Criteria.where("expiry").gt(DateTime.now().toDate())); + long total = this.mongoTemplate.count(query, SiteFile.class); + if (total > 0L) { + page = this.page(total, page, size); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), SiteFile.class); + return new PageImpl(result, pageable, total); + } else { + Pageable pageable = PageRequest.of(0, size); + return new PageImpl(new ArrayList(), pageable, total); + } + } + + public void delete(UUID siteUuid, SiteFile siteFile) { + (new McFile(this.getDeviceFilePath(siteUuid, UUID.fromString((String)siteFile.getFileInfo().get("deviceUuid")), siteFile.getFileUuid()))).delete(); + this.deleteById(SiteFile.class, siteFile.getFileUuid()); + } + + public SiteFile saveFile(UUID fileUuid, String fileName, User user, Site site, Device device, String forWhat) { + try { + if (fileUuid == null) { + fileUuid = UUID.randomUUID(); + } + + String filePath = this.getDeviceFilePath(user.getSiteUuid(), device.getUuid(), fileUuid); + McFile targetFile = new McFile(filePath); + SiteFile siteFile = null; + if (targetFile.exists()) { + siteFile = new SiteFile(user, fileUuid, targetFile); + if (siteFile.getLength() > 0L) { + siteFile.setSiteUuid(site.getUuid()); + siteFile.getFileInfo().put("deviceSerial", device.getSerialNo()); + siteFile.getFileInfo().put("deviceUuid", device.getUuid()); + siteFile.setSiteName(site.getIdName()); + siteFile.setFileName(fileName); + siteFile.setType(targetFile.getContentType()); + siteFile.setLastModified(targetFile.lastModified()); + siteFile.setRequestedFrom(user); + siteFile.setCategory("device_file_pull"); + siteFile.setForWhat("deviceFile_pulling_" + forWhat); + siteFile.setRequested(new Date()); + siteFile.setExpiry((new LocalDate()).plusDays(2).toDate()); + this.save(siteFile); + this.setNotification(siteFile, site); + return siteFile; + } + + targetFile.delete(); + return null; + } + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + public void setNotification(SiteFile siteFile, Site site) { + String deviceSerial = siteFile.getFileInfo().getString("deviceSerial"); + String fileName = siteFile.getFileName(); + User user = siteFile.getRequestedFrom(); + UUID siteUuid = siteFile.getSiteUuid(); + NewsMessage newsMessage = new NewsMessage(); + newsMessage.setCategory(siteFile.getCategory()); + newsMessage.setForWhat(siteFile.getForWhat()); + newsMessage.setMessage("Requested file is ready.", String.format("Device %s, file name : %s", deviceSerial, fileName)); + newsMessage.getReference().put("siteUuid", siteUuid); + newsMessage.getReference().put("deviceSerial", siteFile.getFileInfo().get("deviceSerial")); + newsMessage.getReference().put("deviceUuid", siteFile.getFileInfo().get("deviceUuid")); + newsMessage.getReference().put("fileName", fileName); + newsMessage.getReference().put("fileUuid", siteFile.getFileUuid()); + newsMessage.getReference().put("requestedUser", user.getName()); + newsMessage.setExpiry((new LocalDate()).plusDays(2).toDate()); + newsMessage.setSendNow(false); + this.newsMessageService.save(newsMessage); + this.newsMessageService.setMessageLog(newsMessage, user.getUuid(), siteUuid); + if (site.notifyViaMail()) { + String filePath = siteFile == null ? null : this.getDeviceFilePath(siteFile.getSiteUuid(), UUID.fromString(siteFile.getFileInfo().get("deviceUuid").toString()), siteFile.getFileUuid()); + DateFormat dateFormat = new SimpleDateFormat("EE-MM-dd-yyyy"); + newsMessage.getReference().put("reportExpiry", dateFormat.format(siteFile.getExpiry())); + newsMessage.getReference().put("deviceSerial", deviceSerial); + newsMessage.getReference().put("siteName", siteFile.getSiteName()); + this.emailService.sendDevicePullNotificationRequest(user, newsMessage, filePath, fileName); + } + + } +} diff --git a/src/main/java/com/midm/service/file/FileService.java b/src/main/java/com/midm/service/file/FileService.java new file mode 100644 index 0000000..79bacba --- /dev/null +++ b/src/main/java/com/midm/service/file/FileService.java @@ -0,0 +1,1342 @@ +package com.midm.service.file; + +import com.google.common.base.CharMatcher; +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.ProfileApps; +import com.midm.model.file.AppFile; +import com.midm.model.file.BaseFile; +import com.midm.model.file.FILE_TYPE; +import com.midm.model.file.OtaFile; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.service.BaseService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.ProfileService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.UpdateResult; +import java.awt.image.BufferedImage; +import java.awt.image.ImageObserver; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Pattern; +import javax.imageio.ImageIO; +import javax.servlet.ServletContext; +import org.apache.commons.io.IOUtils; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +@Service("fileService") +public class FileService extends BaseService { + private int profileWidth = 512; + private int profileHeight = 512; + private int logoHeight = 72; + @Autowired + ServletContext servletContext; + @Autowired + private SettingsService settingsService; + @Autowired + @Lazy + protected ProfileService profileService; + @Autowired + private CloudStorageService cloudStorageService; + @Autowired + @Lazy + private HostLicenseService hostLicenseService; + private Map filesMap = new HashMap(); + + public void save(AppFile app) { + app = (AppFile)this.saveDocument(app); + this.filesMap.put(app.getFileUuid(), app); + + for(DeviceProfile profile : this.profileService.findAllByApp(app.getFileUuid())) { + profile.setUpdated(); + this.profileService.save(profile); + } + + } + + public boolean rename(UUID fileUuid, String name, Class entityClass) { + UpdateResult result = this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(fileUuid)), Update.update("name", name), entityClass); + boolean updated = result.getModifiedCount() > 0L; + if (updated) { + BaseFile file = null; + if (entityClass == AppFile.class) { + file = this.findApp(fileUuid, true); + } else if (entityClass == OtaFile.class) { + file = this.findOta(fileUuid); + } else { + file = this.findFile(fileUuid); + } + + if (file != null) { + file.setName(name); + } + } + + return updated; + } + + public boolean nameExists(UUID siteUuid, UUID fileUuid, String name, Class entityClass) { + Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); + if (fileUuid != null) { + criteria.and("_id").ne(fileUuid); + } + + Query query = Query.query(criteria); + return this.mongoTemplate.exists(query, entityClass); + } + + public AppFile findApp(UUID fileUuid, boolean minify) { + if (this.filesMap.containsKey(fileUuid)) { + AppFile file = (AppFile)this.filesMap.get(fileUuid); + file.hasFileUrl(); + file.hasIconUrl(); + return file; + } else { + Query query = Query.query(Criteria.where("_id").is(fileUuid)); + if (minify) { + query.fields().exclude("userUuid").exclude("registeredAt").exclude("lastUpdated").exclude("enabled").exclude("generateIcon").exclude("appInfo.userPermission").exclude("appInfo.targetSdkVersion"); + } + + AppFile appFile = (AppFile)this.mongoTemplate.findOne(query, AppFile.class); + if (appFile != null && !minify) { + this.filesMap.put(fileUuid, appFile); + } + + return appFile; + } + } + + public AppFile findLatest(UUID siteUuid, String packageName) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("appInfo.packageName").is(packageName)); + query.with(Sort.by(Direction.DESC, new String[]{"appInfo.versionCode"})); + return (AppFile)this.mongoTemplate.findOne(query, AppFile.class); + } + + public AppFile findLatest(UUID siteUuid, String packageName, int curVersion) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("appInfo.packageName").is(packageName); + if (curVersion < 1000) { + criteria.andOperator(new Criteria[]{Criteria.where("appInfo.versionCode").gt(curVersion), Criteria.where("appInfo.versionCode").lt(1000)}); + } else { + criteria.and("appInfo.versionCode").gt(curVersion); + } + + Query query = Query.query(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"appInfo.versionCode"})); + return (AppFile)this.mongoTemplate.findOne(query, AppFile.class); + } + + public Collection findApps(Collection uuids, String packageName, int minSdkVersion) { + if (uuids != null && !uuids.isEmpty()) { + if (minSdkVersion == Integer.MAX_VALUE) { + List apps = new ArrayList(); + uuids.forEach((uuid) -> { + AppFile appFile = this.findApp(uuid, false); + if (appFile != null) { + apps.add(appFile); + } + + }); + return apps; + } else { + Map apps = new HashMap(); + uuids.forEach((uuid) -> { + AppFile appFile = this.findApp(uuid, false); + if (appFile != null) { + String appPackage = appFile.getPackageName(); + if (minSdkVersion >= appFile.getMinSdkVersion() && (packageName == null || packageName.equals(appPackage)) && (!apps.containsKey(appPackage) || ((AppFile)apps.get(appPackage)).getVersionCode() < appFile.getVersionCode())) { + apps.put(appPackage, appFile); + } + } + + }); + return apps.values(); + } + } else { + return null; + } + } + + public List findApps(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid); + Query query = Query.query(criteria); + if (jFilter != null && jFilter.size() > 0) { + query.addCriteria(McMongoUtils.toCriteria(jFilter)); + } + + query.fields().exclude("userUuid").exclude("siteUuid").exclude("fileInfo.checksum").exclude("registeredAt").exclude("lastUpdated").exclude("generateIcon").exclude("enabled").exclude("appInfo.userPermission"); + if (!Strings.isNullOrEmpty(sortBy)) { + query.with(Sort.by(direction, new String[]{sortBy})); + } + + query.collation(LocaleConst.COLLATION_DEFAULT); + return this.mongoTemplate.find(query, AppFile.class); + } + + public Page findApps(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "name"; + direction = Direction.ASC; + } + + return this.findByPage(AppFile.class, filter, sortBy, direction, page, size); + } + + public void delete(UUID siteUuid, AppFile... appsArray) { + for(AppFile app : appsArray) { + this.deleteApp(siteUuid, app.getFileUuid()); + } + + } + + public void deleteApp(UUID siteUuid, UUID appUuid) { + this.filesMap.remove(appUuid); + this.deleteById(AppFile.class, appUuid); + String filePath = this.getFilePath(siteUuid, "app", appUuid); + McFile file = new McFile(filePath); + if (file.exists()) { + file.delete(); + } + + file = new McFile(filePath + ".png"); + if (file.exists()) { + file.delete(); + } + + this.cloudStorageService.delete(siteUuid, "app", appUuid); + List profiles = this.profileService.findAllByApp(appUuid); + if (profiles != null && !profiles.isEmpty()) { + for(DeviceProfile profile : profiles) { + ProfileApps apps = profile.getApps(); + if (apps.removeInstallApp(appUuid)) { + if (!apps.hasInstallApps()) { + apps.setInstallApp((List)null); + } + + this.profileService.save(profile); + } + } + } + + } + + public void save(OtaFile otaFile) { + otaFile = (OtaFile)this.saveDocument(otaFile); + this.filesMap.put(otaFile.getFileUuid(), otaFile); + } + + public OtaFile findOta(UUID fileUuid) { + OtaFile otaFile = null; + if (this.filesMap.containsKey(fileUuid)) { + otaFile = (OtaFile)this.filesMap.get(fileUuid); + otaFile.hasFileUrl(); + otaFile.hasIconUrl(); + } + + if (otaFile == null) { + this.filesMap.remove(fileUuid); + otaFile = (OtaFile)this.findById(OtaFile.class, fileUuid); + if (otaFile != null) { + this.filesMap.put(fileUuid, otaFile); + } + } + + return otaFile; + } + + public OtaFile findOta(UUID siteUuid, long buildDate) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("otaInfo.buildDate").is(buildDate)); + return (OtaFile)this.mongoTemplate.findOne(query, OtaFile.class); + } + + public List findOtas(Collection uuids) { + if (uuids != null && !uuids.isEmpty()) { + ArrayList otas = new ArrayList(); + uuids.forEach((uuid) -> { + OtaFile otaFile = this.findOta(uuid); + if (otaFile != null) { + otas.add(otaFile); + } + + }); + return otas; + } else { + return null; + } + } + + public List findOtas(Collection uuids, String deviceId, String skuId, String customerId) { + if (uuids != null && !uuids.isEmpty()) { + ArrayList otas = new ArrayList(); + uuids.forEach((uuid) -> { + OtaFile ota = this.findOta(uuid); + if (ota != null && ota.getDeviceId().equals(deviceId)) { + if (ota.isSystemImage()) { + if (ota.isCompatibleSkuId(skuId)) { + otas.add(ota); + } + } else if (Strings.isNullOrEmpty(customerId) || ota.getCustomerId().equals(customerId)) { + otas.add(ota); + } + } + + }); + return otas; + } else { + return null; + } + } + + public List findOtas(Collection uuids, Device device, boolean checkBuildDate, boolean partialFirst) { + if (uuids != null && !uuids.isEmpty()) { + List otas = this.findOtas(uuids, device.getDeviceId(), device.getSkuId(), device.getCustomerId()); + if (otas != null && !otas.isEmpty()) { + if (otas.size() > 2) { + Collections.sort(otas); + } + + ArrayList bases = new ArrayList(); + ArrayList partials = new ArrayList(); + OtaFile regionImage = null; + String skuId = device.getSkuId(); + long curBuildDate = device.getBuildDate(); + long curRegionBuildDate = device.getRegionBuildDate(); + String curBuild = device.getBuildFingerPrint(); + String scriptVersion = device.getScriptVersion(); + String customerId = device.getCustomerId(); + long partialTotal = 0L; + long baseTotal = 0L; + OtaFile lastBase = null; + OtaFile latest = null; + + for(OtaFile ota : otas) { + if (ota.isSystemImage()) { + if (ota.isCompatibleSkuId(skuId)) { + if (curBuildDate <= ota.getBuildDate()) { + if (ota.isPartial()) { + String preBuild = ota.getPreBuild(); + if (curBuild == null || preBuild.equals(curBuild)) { + partials.add(ota); + curBuild = ota.getPostBuild(); + curBuildDate = ota.getBuildDate(); + partialTotal += ota.getLength(); + } + } else { + if (!bases.isEmpty()) { + boolean clearBase = false; + if (lastBase != null) { + if (lastBase.getBuildDate() < ota.getBuildDate()) { + clearBase = true; + } else { + if (lastBase.getBuildDate() != ota.getBuildDate()) { + continue; + } + + clearBase = baseTotal >= ota.getLength(); + } + } + + if (clearBase) { + bases.clear(); + baseTotal = 0L; + partials.clear(); + partialTotal = 0L; + } + } + + if (!partials.isEmpty()) { + if (curBuildDate >= ota.getBuildDate() && (partialFirst || partialTotal < ota.getLength())) { + bases.addAll(partials); + baseTotal += partialTotal; + partials.clear(); + partialTotal = 0L; + if (!partialFirst && baseTotal > ota.getLength()) { + bases.clear(); + baseTotal = ota.getLength(); + bases.add(ota); + } + continue; + } + + partials.clear(); + partialTotal = 0L; + } + + lastBase = ota; + bases.add(ota); + curBuild = ota.getPostBuild(); + baseTotal += ota.getLength(); + } + } else if (latest == null || latest.getBuildDate() < ota.getBuildDate()) { + latest = ota; + } + } + } else if ((Strings.isNullOrEmpty(customerId) || ota.getCustomerId().equals(customerId)) && !ota.getScriptVersion().equals(scriptVersion)) { + if (checkBuildDate) { + if (curRegionBuildDate < ota.getBuildDate() && (regionImage == null || regionImage.getBuildDate() < ota.getBuildDate())) { + regionImage = ota; + } + } else if (regionImage == null) { + regionImage = ota; + } + } + } + + if (!partials.isEmpty()) { + bases.addAll(partials); + } + + if (bases.isEmpty() && latest != null) { + bases.add(latest); + } + + Iterator it = bases.iterator(); + + while(it.hasNext()) { + OtaFile info = (OtaFile)it.next(); + if (info.getBuildDate() <= device.getBuildDate()) { + it.remove(); + } + } + + if (regionImage != null) { + bases.add(0, regionImage); + } + + return bases; + } else { + return null; + } + } else { + return null; + } + } + + public OtaFile findOta(List uuids, String deviceId, String skuId, String customerId, String scriptVersion, long regionBuildDate, String fingerPrint, long buildDate, boolean partialFirst, boolean ignorePartNo, boolean checkBuildDate) { + List partialOtas = new ArrayList(); + OtaFile fullImage = null; + OtaFile partialImage = null; + OtaFile regionImage = null; + List otas = this.findOtas((Collection)uuids, (String)deviceId, skuId, (String)customerId); + if (otas != null && !otas.isEmpty()) { + if (otas.size() > 2) { + Collections.sort(otas); + } + + for(OtaFile ota : otas) { + if (ota != null && ota.getDeviceId().equals(deviceId)) { + if (ota.isSystemImage()) { + if (ota.getBuildDate() > buildDate && ota.isCompatibleSkuId(skuId)) { + if (ota.isPartial()) { + partialOtas.add(ota); + if (partialImage == null && ota.getPreBuild().equals(fingerPrint)) { + partialImage = ota; + } + } else if (fullImage == null || fullImage.getBuildDate() < ota.getBuildDate()) { + fullImage = ota; + } + } + } else if (ota.isRegionImage() && (Strings.isNullOrEmpty(customerId) || ota.getCustomerId().equals(customerId)) && !ota.getScriptVersion().equals(scriptVersion)) { + if (!checkBuildDate) { + return ota; + } + + if (ota.getBuildDate() > regionBuildDate && (regionImage == null || regionImage.getBuildDate() < ota.getBuildDate())) { + regionImage = ota; + } + } + } + } + + if (regionImage != null) { + return regionImage; + } else if (fullImage == null) { + return partialImage; + } else if (partialImage == null) { + return fullImage; + } else { + OtaFile finalPartial = partialImage; + long totalPartialLength = partialImage.getLength(); + partialOtas.remove(partialImage); + if (!partialOtas.isEmpty()) { + if (partialOtas.size() == 1) { + finalPartial = (OtaFile)partialOtas.get(0); + totalPartialLength += finalPartial.getLength(); + } else { + partialOtas.sort((ota1, ota2) -> Long.compare(ota1.getBuildDate(), ota2.getBuildDate())); + Iterator it = partialOtas.iterator(); + + while(it.hasNext()) { + OtaFile otaFile = (OtaFile)it.next(); + if (finalPartial != null && !otaFile.getPreBuild().equals(finalPartial.getPostBuild())) { + it.remove(); + } else if (fullImage == null || fullImage.getBuildDate() >= otaFile.getBuildDate()) { + finalPartial = otaFile; + totalPartialLength += otaFile.getLength(); + } + } + } + } + + if (fullImage.getBuildDate() > finalPartial.getBuildDate()) { + return fullImage; + } else if (fullImage.getBuildDate() < finalPartial.getBuildDate()) { + return partialImage; + } else if (partialFirst) { + return partialImage; + } else { + return totalPartialLength < fullImage.getLength() ? partialImage : fullImage; + } + } + } else { + return null; + } + } + + public Page findOtas(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "name"; + direction = Direction.ASC; + } + + return this.findByPage(OtaFile.class, filter, sortBy, direction, page, size); + } + + public List findAvailableOtas(String productId, Long buildDate, String otaCert) { + Query query = new Query(); + if (buildDate == null) { + buildDate = 0L; + } + + Criteria criteria = Criteria.where("otaInfo.productId").regex(Pattern.compile(productId, 66)).and("otaInfo.otaCert").regex(Pattern.compile(otaCert, 66)).and("otaInfo.buildDate").gte(buildDate).and("siteUuid").exists(false); + query.addCriteria(criteria); + List result = this.mongoTemplate.find(query, OtaFile.class); + + for(OtaFile otaFile : result) { + if (Strings.isNullOrEmpty(otaFile.getFileUrl())) { + String fileUrl = String.format("/%s/%s", otaFile.getFileUuid(), otaFile.getFileName()); + otaFile.setFileUrl(fileUrl); + } + } + + return result; + } + + public boolean matchOta(UUID fileUuid, String otaCert) { + OtaFile otaFile = (OtaFile)this.findById(OtaFile.class, fileUuid); + return otaFile.getOtaCertHash().equals(otaCert); + } + + public List findOtas(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid); + Query query = Query.query(criteria); + if (jFilter != null && jFilter.size() > 0) { + query.addCriteria(McMongoUtils.toCriteria(jFilter)); + } + + if (!Strings.isNullOrEmpty(sortBy)) { + query.with(Sort.by(direction, new String[]{sortBy})); + } + + query.fields().exclude("userUuid").exclude("siteUuid").exclude("fileInfo.checksum").exclude("registeredAt").exclude("lastUpdated").exclude("enabled"); + return this.mongoTemplate.find(query, OtaFile.class); + } + + public void delete(UUID siteUuid, OtaFile otaFile) { + UUID fileUuid = otaFile.getFileUuid(); + this.deleteById(OtaFile.class, fileUuid); + (new McFile(this.getFilePath(siteUuid, "ota", fileUuid))).delete(); + this.cloudStorageService.delete(siteUuid, "ota", fileUuid); + List profiles = this.profileService.findAllByOta(fileUuid); + if (profiles != null && !profiles.isEmpty()) { + boolean isUpdated = false; + + for(DeviceProfile profile : profiles) { + List otas = profile.getOtas(); + if (otas.contains(fileUuid)) { + otas.remove(fileUuid); + isUpdated = true; + } + + if (otas.isEmpty()) { + profile.setOtas((List)null); + } + + if (isUpdated) { + this.profileService.save(profile); + } + } + } + + this.filesMap.remove(fileUuid); + } + + public BaseFile findFile(UUID fileUuid) { + if (this.filesMap.containsKey(fileUuid)) { + BaseFile file = (BaseFile)this.filesMap.get(fileUuid); + file.hasFileUrl(); + file.hasIconUrl(); + return file; + } else { + BaseFile file = (BaseFile)this.findById(BaseFile.class, fileUuid); + if (file != null) { + this.filesMap.put(fileUuid, file); + } + + return file; + } + } + + public List findFiles(Collection uuids) { + if (uuids != null && !uuids.isEmpty()) { + ArrayList files = new ArrayList(); + uuids.forEach((uuid) -> { + BaseFile file = this.findFile(uuid); + if (file != null) { + files.add(file); + } + + }); + return files; + } else { + return null; + } + } + + public void save(BaseFile file) { + file = (BaseFile)this.saveDocument(file); + this.filesMap.put(file.getFileUuid(), file); + } + + public boolean fileNameExists(UUID fileUuid, String name, UUID siteUuid) { + Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); + Query query = Query.query(criteria); + BaseFile file = (BaseFile)this.mongoTemplate.findOne(query, BaseFile.class); + return file != null && !file.getFileUuid().equals(fileUuid); + } + + public String getFileName(UUID fileUuid, FILE_TYPE type) { + BaseFile file = (BaseFile)this.filesMap.get(fileUuid); + if (file != null) { + return file.getFileName(); + } else { + if (type == FILE_TYPE.OTA) { + file = this.findOta(fileUuid); + } else if (type == FILE_TYPE.APK) { + file = this.findApp(fileUuid, false); + } else { + file = this.findFile(fileUuid); + } + + return file != null ? file.getFileName() : null; + } + } + + public List findFiles(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid); + Query query = Query.query(criteria); + if (jFilter != null && jFilter.size() > 0) { + query.addCriteria(McMongoUtils.toCriteria(jFilter)); + } + + if (!Strings.isNullOrEmpty(sortBy)) { + query.with(Sort.by(direction, new String[]{sortBy})); + } + + query.fields().exclude("userUuid").exclude("siteUuid").exclude("fileInfo.checksum").exclude("registeredAt").exclude("lastUpdated").exclude("enabled"); + return this.mongoTemplate.find(query, BaseFile.class); + } + + public Page findFiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "name"; + direction = Direction.ASC; + } + + return this.findByPage(BaseFile.class, filter, sortBy, direction, page, size); + } + + public void delete(UUID siteUuid, BaseFile file) { + UUID fileUuid = file.getFileUuid(); + this.deleteById(BaseFile.class, fileUuid); + (new McFile(this.getFilePath(siteUuid, "other", fileUuid))).delete(); + this.cloudStorageService.delete(siteUuid, "other", fileUuid); + String uuidString = fileUuid.toString(); + List profiles = this.profileService.findAllByFile(fileUuid); + if (profiles != null && !profiles.isEmpty()) { + Iterator it = profiles.iterator(); + + while(it.hasNext()) { + boolean isUpdated = false; + DeviceProfile profile = (DeviceProfile)it.next(); + DbObject dbSettings = (DbObject)profile.getSetting("system", "display"); + if (dbSettings != null && dbSettings.containsKey("wallpaper") && dbSettings.get("wallpaper").equals(uuidString)) { + dbSettings.remove("wallpaper"); + isUpdated = true; + } + + if (!isUpdated) { + DbObject files = profile.getFiles(); + if (files != null) { + List pushFiles = files.getList("push", DbObject.class); + if (pushFiles != null && !pushFiles.isEmpty()) { + Iterator itPushFiles = pushFiles.iterator(); + + while(itPushFiles.hasNext()) { + DbObject pushFile = (DbObject)itPushFiles.next(); + List sources = pushFile.getList("sources", Object.class); + if (sources != null) { + Iterator itSources = sources.iterator(); + + while(itSources.hasNext()) { + Object source = itSources.next(); + if (source.equals(uuidString)) { + itSources.remove(); + isUpdated = true; + } + } + + if (sources.size() == 0) { + itPushFiles.remove(); + } + } + } + } + + if (pushFiles == null || pushFiles.isEmpty()) { + files.remove("push"); + } + } + + if (files == null || files.isEmpty()) { + profile.setFiles((DbObject)null); + } + } + + if (isUpdated) { + profile.setUpdated(); + this.profileService.save(profile); + } + } + } + + this.filesMap.remove(fileUuid); + } + + public String getUserProfilePath(UUID userUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "user", new Object[]{userUuid, "profile"}); + } + + public String getUserFilePath(UUID userUuid, UUID fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "user", new Object[]{userUuid, "other", fileUuid}); + } + + public String getUserFilePath(UUID userUuid, String category, UUID fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "user", new Object[]{userUuid, category, fileUuid}); + } + + public String getFilePath(String fileType, UUID fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), fileType, new Object[]{fileUuid}); + } + + public String getFilePath(UUID siteUuid, String fileType, UUID fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid != null ? siteUuid : "system", new Object[]{fileType, fileUuid}); + } + + public String getFilePath(String siteUuid, String fileType, String fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid != null ? siteUuid : "system", new Object[]{fileType, fileUuid}); + } + + public String getDeviceFilePath(UUID siteUuid, UUID deviceUuid, String fileType, Object fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "device", new Object[]{siteUuid, deviceUuid, fileType, fileUuid}); + } + + public String getDeviceFilePath(UUID siteUuid, UUID deviceUuid, Object fileUuid) { + return this.getDeviceFilePath(siteUuid, deviceUuid, "file", fileUuid); + } + + public String getSiteFilePath(UUID siteUuid, String fileType) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid == null ? "unknown" : siteUuid, new Object[]{fileType}); + } + + public String getMustFolderRootPath(UUID siteUuid, UUID profileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid, new Object[]{profileUuid}); + } + + public String getMustDownloadFilePath(UUID siteUuid, UUID profileUuid, String tempPath) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid, new Object[]{tempPath, profileUuid}); + } + + public String getMustDownloadProfilePath(UUID siteUuid, UUID profileUuid, String tempPath, String fileName) { + return Joiner.on('/').join(this.getMustDownloadFilePath(siteUuid, profileUuid, tempPath), fileName, new Object[0]); + } + + public String getMustFolderFilePath(UUID siteUuid, UUID profileUuid, String path) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid, new Object[]{profileUuid, path}); + } + + public String getBackgroundPath() { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "system", new Object[]{"background.jpg"}); + } + + public String getFaviconPath() { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "system", new Object[]{"favicon.png"}); + } + + public File getReportTemplate(String fileName) { + String path = Joiner.on('/').join(this.settingsService.getFilesRootPath(), "report", new Object[]{fileName}); + McFile file = new McFile(path); + return file.exists() ? file : this.getResourceFile("report/" + fileName, false); + } + + public BufferedImage getProfileImage(MultipartFile file) { + try { + BufferedImage image = ImageIO.read(file.getInputStream()); + return this.generateThumbnail(image, this.profileWidth, this.profileHeight); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public BufferedImage getLogoImage(MultipartFile file) { + try { + BufferedImage image = ImageIO.read(file.getInputStream()); + int height = image.getHeight() > this.logoHeight ? this.logoHeight : image.getHeight(); + float ratio = (float)height / (float)image.getHeight(); + int width = Math.round((float)image.getWidth() * ratio); + return this.generateThumbnail(image, width, height); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public BufferedImage getBgImage(MultipartFile file) { + try { + BufferedImage image = ImageIO.read(file.getInputStream()); + int width = image.getWidth(); + return width <= 1080 ? image : this.scaledImage(image, 1080.0F / (float)width); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public BufferedImage scaledImage(BufferedImage image, float scale) { + int width = (int)((float)image.getWidth() * scale); + int height = (int)((float)image.getHeight() * scale); + BufferedImage scaledImage = new BufferedImage(width, height, 1); + scaledImage.createGraphics().drawImage(image, 0, 0, width, height, (ImageObserver)null); + scaledImage.getGraphics().dispose(); + return scaledImage; + } + + public BufferedImage generateThumbnail(BufferedImage image, int width, int height) { + int orgWidth = image.getWidth(); + int orgHeight = image.getHeight(); + float targetRatio = (float)width / (float)height; + float orgRatio = (float)orgWidth / (float)orgHeight; + BufferedImage thumbnail = new BufferedImage(width, height, 1); + if (targetRatio == orgRatio) { + thumbnail.createGraphics().drawImage(image, 0, 0, width, height, (ImageObserver)null); + } else { + int scaledWidth = orgWidth; + int scaledHeight = orgHeight; + if (targetRatio > orgRatio) { + scaledHeight = orgWidth; + } else { + scaledWidth = orgHeight; + } + + int offsetX = (orgWidth - scaledWidth) / 2; + int offsetY = (orgHeight - scaledHeight) / 2; + thumbnail.createGraphics().drawImage(image, 0, 0, width, height, offsetX, offsetY, offsetX + scaledWidth, offsetY + scaledHeight, (ImageObserver)null); + } + + thumbnail.getGraphics().dispose(); + return thumbnail; + } + + public Map sync() { + Map deleted = new HashMap(); + McFile filesRoot = new McFile(this.settingsService.getFilesRootPath()); + File[] rootFiles = filesRoot.listFiles(); + if (rootFiles != null && rootFiles.length != 0) { + for(File file : rootFiles) { + switch (file.getName()) { + case "keyStore": + case "report": + case "system": + case "store": + break; + case "user": + Object clearedUser = this.clearUserFiles(); + if (clearedUser != null) { + deleted.put("user", clearedUser); + } + break; + default: + Object clearedFile = this.clearSite(file); + if (clearedFile != null) { + deleted.put(file.getName(), clearedFile); + } + } + } + } else { + deleted.put("result", "No file exists"); + } + + return deleted; + } + + private Object clearSite(File siteFolder) { + UUID siteUuid = null; + + try { + siteUuid = UUID.fromString(siteFolder.getName()); + } catch (IllegalArgumentException var12) { + return "Not UUID format."; + } + + if (!this.existsById(Site.class, siteUuid)) { + this.cloudStorageService.delete(siteUuid); + return !siteFolder.delete() ? "Not existing site but can't remove." : "Not existing site, removed."; + } else { + Map siteResults = new HashMap(); + File[] siteFiles = siteFolder.listFiles(); + if (siteFiles != null && siteFiles.length != 0) { + File[] var5 = siteFiles; + int var6 = siteFiles.length; + int var7 = 0; + + while(var7 < var6) { + File file = var5[var7]; + switch (file.getName()) { + default: + File[] files = file.listFiles(); + if (files != null && files.length > 0) { + Map results = this.clearSiteFiles(siteUuid, category, files); + if (!results.isEmpty()) { + siteResults.put(category, results); + } + } else { + siteResults.put(category, "No category files."); + } + case "profile": + case "logo": + case "background": + ++var7; + } + } + } else { + siteResults.put("result", "No site files exists."); + } + + return siteResults.isEmpty() ? null : siteResults; + } + } + + private Map clearSiteFiles(UUID siteUuid, String category, File[] categoryFiles) { + Map removed = new HashMap(); + + for(File file : categoryFiles) { + UUID uuid = null; + + try { + uuid = UUID.fromString(file.getName()); + } catch (Exception var13) { + if (category.equals("app")) { + McFile tempFile = new McFile(file); + if (tempFile.getName().endsWith(".png") && !(new McFile(file.getParent(), (new McFile(file)).getNameWithoutExtension())).exists()) { + tempFile.delete(); + this.cloudStorageService.delete(siteUuid, category, tempFile.getName()); + } + } + continue; + } + + BaseFile siteFile = null; + switch (category) { + case "app": + siteFile = (BaseFile)this.findById(AppFile.class, uuid); + break; + case "ota": + siteFile = (BaseFile)this.findById(OtaFile.class, uuid); + break; + case "other": + siteFile = (BaseFile)this.findById(BaseFile.class, uuid); + break; + case "device": + return this.clearDeviceFiles(siteUuid, file); + } + + if (siteFile == null) { + if (file.delete()) { + if (category.equals("app")) { + (new McFile(file, ".png")).delete(); + } + + removed.put(file.getPath(), "Not existing file, removed."); + } else { + removed.put(file.getPath(), "Not exiting file but can't Remove."); + } + + this.cloudStorageService.delete(siteUuid, category, file.getName()); + } else if (!this.cloudStorageService.keepInLocal() && !category.equals("device")) { + file.delete(); + } + } + + return removed; + } + + public Map clearDeviceFiles(UUID siteUuid, File deviceFolder) { + Map removed = new HashMap(); + UUID deviceUuid = UUID.fromString(deviceFolder.getName()); + if (this.existsById(Device.class, deviceUuid)) { + this.cloudStorageService.delete(siteUuid, "device", deviceUuid); + File[] deviceFiles = deviceFolder.listFiles(); + if (deviceFiles != null && deviceFiles.length > 0) { + long expiry = LocalDate.now().minusDays(1).toDate().getTime(); + + for(File file : deviceFiles) { + if (file.lastModified() < expiry) { + file.delete(); + removed.put(file.getPath(), "Too old file, removed"); + } + } + } + } else { + if ((new McFile(deviceFolder)).delete()) { + removed.put(deviceFolder.getPath(), "Not existing device, removed."); + } else { + removed.put(deviceFolder.getPath(), "Not exiting device but can't Remove."); + } + + this.cloudStorageService.delete(siteUuid, "device", deviceUuid); + } + + return removed; + } + + @Scheduled( + cron = "0 15 0 * * *" + ) + @Async + public Object clearUserFiles() { + if (!this.hostLicenseService.isPrimaryServer()) { + return null; + } else { + McFile userRoot = new McFile(this.settingsService.getFilesRootPath(), "user"); + long expiry = LocalDate.now().minusDays(1).toDate().getTime(); + Map deleted = new HashMap(); + File[] userFiles = userRoot.listFiles(); + if (userFiles != null && userFiles.length != 0) { + for(File userFolder : userFiles) { + UUID userUuid = UUID.fromString(userFolder.getName()); + if (this.existsById(User.class, userUuid)) { + McFile otherFolder = new McFile(userFolder, "other"); + if (otherFolder.exists()) { + File[] otherFiles = otherFolder.listFiles(); + if (otherFiles != null && otherFiles.length != 0) { + for(File file : otherFiles) { + if (file.lastModified() < expiry) { + if (file.delete()) { + deleted.put(file.getPath(), "Removed."); + } else { + deleted.put(file.getPath(), "Not removed."); + } + } + } + } + + otherFiles = otherFolder.listFiles(); + if (otherFiles == null || otherFiles.length == 0) { + if ((new McFile(otherFolder)).delete()) { + deleted.put(otherFolder.getPath(), "Other folder is empty, removed."); + } else { + deleted.put(otherFolder.getPath(), "Other folder is empty but not removed."); + } + } + } + } else if ((new McFile(userFolder)).delete()) { + deleted.put(userFolder.getName(), "User not exists, removed."); + } else { + deleted.put(userFolder.getName(), "User not exists but not removed."); + } + + if (userFolder.list() == null || userFolder.list().length == 0) { + if ((new McFile(userFolder)).delete()) { + deleted.put(userFolder.getName(), "User folder is empty, removed."); + } else { + deleted.put(userFolder.getName(), "User folder is empty but not removed."); + } + } + } + } else { + deleted.put("result", "No user folder exists."); + } + + return deleted.isEmpty() ? null : deleted; + } + } + + public void syncLocalToCloud() { + List appFiles = this.findAll(AppFile.class); + this.updateMetaInfo("app", appFiles); + List otaFiles = this.findAll(OtaFile.class); + this.updateMetaInfo("ota", otaFiles); + List otherFiles = this.findAll(BaseFile.class); + this.updateMetaInfo("other", otherFiles); + } + + public void updateMetaInfo(String category, List files) { + for(Object objectFile : files) { + BaseFile baseFile = (BaseFile)objectFile; + UUID siteUuid = baseFile.getSiteUuid(); + UUID fileUuid = baseFile.getFileUuid(); + String fileName = baseFile.getFileName(); + Object[] paths = new Object[]{siteUuid, category, baseFile.getFileUuid()}; + if (this.cloudStorageService.exists(paths)) { + this.cloudStorageService.updateMetaInfo(fileName, baseFile.getContentType(), paths); + if (category.equals("app")) { + paths = new Object[]{siteUuid, category, fileUuid.toString() + ".png"}; + if (this.cloudStorageService.exists(paths)) { + McFile var10000 = new McFile(fileName); + fileName = var10000.getNameWithoutExtension() + ".png"; + this.cloudStorageService.updateMetaInfo(fileName, "image/png", paths); + } + } + } else { + String filePath = this.getFilePath(siteUuid, category, fileUuid); + McFile file = new McFile(filePath); + if (file.exists()) { + this.cloudStorageService.upload(file, fileName, baseFile.getContentType(), paths); + } + } + } + + } + + public void syncCloudToLocal() { + for(Object object : this.cloudStorageService.list()) { + if (object instanceof String) { + } + } + + } + + public String getDateStr() { + return McDateTimeUtils.toString(DateTime.now(), "yyyMMdd"); + } + + public String getDateTimeStr() { + return McDateTimeUtils.toString(DateTime.now(), "yyMMddHHmmss"); + } + + public String getDateTimeStr(int offsetMins) { + DateTime now = DateTime.now().plusMinutes(-offsetMins); + return McDateTimeUtils.toString(now, "yyMMddHHmmss"); + } + + public int getDeviceQty(UUID groupUuid, List allDeviceGroup) { + int deviceCount = 0; + + for(DeviceGroup singleDeviceGroup : allDeviceGroup) { + if (groupUuid.equals(singleDeviceGroup.getParentUuid())) { + deviceCount = deviceCount + singleDeviceGroup.getDeviceNumbers() + this.getDeviceQty(singleDeviceGroup.getUuid(), allDeviceGroup); + } + } + + return deviceCount; + } + + public List getFileList(UUID siteUuid, UUID profileUuid, String path) { + if (path.equalsIgnoreCase("root")) { + path = ""; + } + + String filePath = this.getMustFolderFilePath(siteUuid, profileUuid, path); + List jObject = new ArrayList(); + File[] fileList = (new McFile(filePath)).listFiles(); + + for(File fileItem : fileList) { + McFile file = new McFile(fileItem); + Map status = new HashMap(); + status.put("name", file.getName()); + String[] tempPath = file.getPath().split("/", 6); + status.put("path", tempPath[5]); + status.put("lastModified", file.lastModified()); + status.put("length", file.length()); + status.put("isDirectory", file.isDirectory()); + status.put("isFile", file.isFile()); + jObject.add(status); + } + + return jObject; + } + + public void addFolder(UUID siteUuid, UUID profileUuid, String path, String newFolder) { + if (path.equalsIgnoreCase("root")) { + path = ""; + } + + String filePath = this.getMustFolderFilePath(siteUuid, profileUuid, path + "/" + newFolder); + (new McFile(filePath)).mkdirs(); + } + + public void deleteFiles(UUID siteUuid, UUID profileUuid, String path) { + if (path.equalsIgnoreCase("root")) { + path = ""; + } + + String filePath = this.getMustFolderFilePath(siteUuid, profileUuid, path); + (new McFile(filePath)).delete(); + } + + public McFile getResourceFile(String resourcePath, boolean isStatic) { + ClassPathResource resource = new ClassPathResource((isStatic ? "static" : "") + resourcePath); + + try { + return new McFile(resource.getFile().getPath()); + } catch (Exception var5) { + return null; + } + } + + public boolean resourceExists(String resourcePath, boolean isStatic) { + ClassPathResource resource = this.classPathResource(resourcePath, isStatic); + return resource.exists(); + } + + public String getResourceToString(String resourcePath, boolean isStatic) { + ClassPathResource resource = this.classPathResource(resourcePath, isStatic); + + try { + if (resource.exists()) { + InputStream input = resource.getInputStream(); + String helpTemplate = IOUtils.toString(input, Charset.defaultCharset()); + input.close(); + return helpTemplate; + } + } catch (Exception var6) { + } + + return null; + } + + private ClassPathResource classPathResource(String resourcePath, boolean isStatic) { + return new ClassPathResource((isStatic ? "static" : "") + resourcePath); + } + + public UpdateResult updateExtras(Class classType, UUID uuid, Map parameterMap) { + Query query = Query.query(Criteria.where("_id").is(uuid)); + Update update = new Update(); + parameterMap.forEach((key, values) -> { + if (key.startsWith("extra.")) { + if (Strings.isNullOrEmpty(values[0])) { + update.unset(key); + } else { + update.set(key, values[0]); + } + } + + }); + return this.mongoTemplate.updateFirst(query, update, classType); + } + + public static enum KEY { + serial_no, + group, + device_group, + owner, + license, + profiles, + product_id, + device_id, + ssid, + ip_addr, + wifi_mac, + bluetooth_mac, + phone_carrier, + build_number, + model_number, + battery_status, + phone_imei, + installed_apps, + imei, + build_date, + enrollment_date, + last_checked_in, + last_updated, + enabled, + model, + display_id, + profile_group, + priority, + is_global, + created, + white_list, + black_list, + applicable_time, + repeat, + hide_status_bar, + hide_nav_bar, + hide_notifications, + wifi_ssid, + apn, + device, + profile, + license_order, + license_detail, + device_customize, + profile_customize, + site_general, + site_devices, + unknown; + + public static KEY get(String key) { + try { + return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); + } catch (Exception var2) { + return unknown; + } + } + } +} diff --git a/src/main/java/com/midm/service/file/ReportService.java b/src/main/java/com/midm/service/file/ReportService.java new file mode 100644 index 0000000..562df87 --- /dev/null +++ b/src/main/java/com/midm/service/file/ReportService.java @@ -0,0 +1,1605 @@ +package com.midm.service.file; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.GeneralProfile; +import com.midm.model.device.AppInfo; +import com.midm.model.device.DataUsage; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceApps; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceLicense; +import com.midm.model.device.DeviceNote; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.ProfileApps; +import com.midm.model.file.AppFile; +import com.midm.model.file.OtaFile; +import com.midm.model.org.Site; +import com.midm.model.org.SiteFile; +import com.midm.model.org.SiteLicense; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.service.Aggregations; +import com.midm.service.device.DeviceService; +import com.midm.service.news.NewsMessageService; +import com.midm.service.org.SiteLicenseService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.doc.ExcelWriter; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.AggregateIterable; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringJoiner; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.poi.ss.usermodel.BuiltinFormats; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.VerticalAlignment; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFRichTextString; +import org.bson.Document; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.joda.time.Days; +import org.joda.time.LocalDate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.AddFieldsOperation; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.aggregation.ProjectionOperation; +import org.springframework.data.mongodb.core.aggregation.SortOperation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.util.CloseableIterator; +import org.springframework.data.util.Pair; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service("reportService") +public class ReportService extends FileService { + private static final String NONE = "-"; + @Autowired + private DeviceService deviceService; + @Autowired + private UserService userService; + @Autowired + private NewsMessageService newsMesageSerivce; + @Autowired + private SiteService siteService; + @Autowired + private SettingsService settingsService; + @Autowired + private SiteLicenseService siteLicenseService; + @Autowired + private FileService fileService; + @Autowired + @Lazy + private HostLicenseService hostLicenseService; + private static final Map hashesMap = new HashMap(); + + public void save(SiteFile file) { + this.mongoTemplate.save(file); + } + + public SiteFile findReportByUuid(UUID uuid) { + return (SiteFile)this.findById(SiteFile.class, uuid); + } + + public Page findReports(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "requested"; + direction = Direction.DESC; + } + + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + query.addCriteria(Criteria.where("expiry").gt(DateTime.now().toDate())); + long total = this.mongoTemplate.count(query, SiteFile.class); + if (total > 0L) { + page = this.page(total, page, size); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), SiteFile.class); + return new PageImpl(result, pageable, total); + } else { + Pageable pageable = PageRequest.of(0, size); + return new PageImpl(new ArrayList(), pageable, total); + } + } + + public void delete(SiteFile siteReport) { + this.mongoTemplate.remove(siteReport); + (new McFile(this.getFilePath(siteReport.getSiteUuid(), "report", siteReport.getFileUuid()))).delete(); + } + + public Document installedApps(UUID siteUuid) { + List pipeline = Arrays.asList(new Document("$lookup", (new Document("from", "device")).append("foreignField", "_id").append("localField", "_id").append("as", "device")), new Document("$match", (new Document("device.siteUuid", siteUuid)).append("category", "installed")), new Document("$project", new Document("packages", new Document("$arrayToObject", new Document("$map", (new Document("input", "$apps")).append("as", "app").append("in", (new Document("k", "$$app.packageName")).append("v", new Document("$cond", Arrays.asList(new Document("$gt", Arrays.asList("$$app.label", null)), "$$app.label", "$$app.packageName")))))))), new Document("$group", (new Document("_id", (Object)null)).append("apps", new Document("$addToSet", "$packages"))), new Document("$replaceRoot", new Document("newRoot", new Document("$mergeObjects", "$apps")))); + AggregateIterable results = this.getCollection(DeviceApps.class).aggregate(pipeline); + Document result = (Document)results.first(); + return result == null ? new Document() : result; + } + + private Collection installedPackages(List deviceUuids) { + List pipeline = Arrays.asList(new Document("$match", new Document("$and", Arrays.asList(new Document("_id", new Document("$in", deviceUuids)), new Document("category", "installed")))), new Document("$project", new Document("packages", new Document("$arrayToObject", new Document("$map", (new Document("input", "$apps")).append("as", "app").append("in", (new Document("k", "$$app.packageName")).append("v", new Document("$cond", Arrays.asList(new Document("$gt", Arrays.asList("$$app.label", null)), "$$app.label", "$$app.packageName")))))))), new Document("$group", (new Document("_id", (Object)null)).append("apps", new Document("$addToSet", "$packages"))), new Document("$replaceRoot", new Document("newRoot", new Document("$mergeObjects", "$apps")))); + AggregateIterable results = this.getCollection(DeviceApps.class).aggregate(pipeline); + Document result = (Document)results.first(); + return (Collection)(result == null ? new ArrayList() : result.keySet()); + } + + private Collection getDevicesForReport(UUID siteUuid, List deviceGroups) { + List matches = new ArrayList(); + matches.add(new Document("siteUuid", siteUuid)); + if (deviceGroups != null) { + if (deviceGroups.isEmpty()) { + matches.add(new Document("deviceGroup", new Document("$exists", false))); + } else { + Collection groups = this.deviceService.findGroupUUids(deviceGroups); + matches.add(new Document("deviceGroup.$id", new Document("$in", groups))); + } + } + + AggregationOperation matchOp = Aggregations.newOperation(new Document("$match", new Document("$and", matches))); + AggregationOperation sortOp = new SortOperation(Sort.by(Direction.ASC, new String[]{"profile.hardware_info.serial_no"})); + AggregationOperation lookupOp = Aggregations.newOperation(new Document("$lookup", (new Document("from", "deviceApps")).append("let", new Document("deviceId", "$_id")).append("pipeline", Arrays.asList(new Document("$match", new Document("$and", Arrays.asList(new Document("$expr", new Document("$eq", Arrays.asList("$category", "installed"))), new Document("$expr", new Document("$eq", Arrays.asList("$_id", "$$deviceId")))))))).append("as", "installedApps"))); + AggregationOperation setOp = Aggregations.newOperation(new Document("$set", new Document("installedApps", new Document("$first", "$installedApps.apps")))); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{matchOp, sortOp, lookupOp, setOp}).withOptions(Aggregation.newAggregationOptions().collation(LocaleConst.COLLATION_DEFAULT).build()); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, Device.class, Device.class); + List devices = results.getMappedResults(); + if (!devices.isEmpty()) { + devices = new ArrayList(devices); + Map pathMap = new HashMap(); + devices.forEach((device) -> { + DeviceGroup group = device.getDeviceGroup(); + if (group != null) { + UUID groupUuid = group.getUuid(); + if (pathMap.containsKey(groupUuid)) { + device.setGroupPath((String)pathMap.get(groupUuid)); + } else { + String groupPath = this.deviceService.getGroupPath(group); + pathMap.put(groupUuid, groupPath); + device.setGroupPath(groupPath); + } + } + + }); + devices.sort((d1, d2) -> { + String path1 = d1.getGroupPath(); + String path2 = d2.getGroupPath(); + if (path1 == null) { + return path2 == null ? d1.getSerialNo().compareTo(d2.getSerialNo()) : -1; + } else if (path2 == null) { + return 1; + } else { + int result = path1.compareToIgnoreCase(path2); + if (result == 0) { + result = d1.getSerialNo().compareTo(d2.getSerialNo()); + } + + return result; + } + }); + } + + return devices; + } + + private List getDataUsages(Collection uuids, boolean wifiUsage, boolean mobileUsage, Date from, Date to) { + if (!wifiUsage && !mobileUsage) { + return new ArrayList(); + } else { + Document matches = (new Document("deviceUuid", new Document("$in", uuids))).append("from", new Document("$gte", from)).append("to", new Document("$lt", to)); + Document matchStage = new Document("$match", matches); + AggregationOperation matchOp = Aggregations.newOperation(matchStage); + SortOperation sortOp = new SortOperation(Sort.by(Direction.ASC, new String[]{"to"})); + List wifiSum = Arrays.asList("$usage.wifi.rx", "$usage.wifi.tx"); + List mobileSum = Arrays.asList("$usage.mobile.rx", "$usage.mobile.tx"); + Document groups = (new Document("_id", "$deviceUuid")).append("from", new Document("$first", "$from")).append("to", new Document("$last", "$to")); + if (wifiUsage) { + groups.append("wifiTotal", new Document("$sum", new Document("$sum", wifiSum))); + } + + if (mobileUsage) { + groups.append("mobileTotal", new Document("$sum", new Document("$sum", mobileSum))); + } + + Document groupStage = new Document("$group", groups); + AggregationOperation groupOp = Aggregations.newOperation(groupStage); + AddFieldsOperation.AddFieldsOperationBuilder addFieldBuilder = AddFieldsOperation.builder(); + if (wifiUsage) { + addFieldBuilder.addFieldWithValue("usage.wifi.total", "$wifiTotal"); + } + + if (mobileUsage) { + addFieldBuilder.addFieldWithValue("usage.mobile.total", "$mobileTotal"); + } + + AddFieldsOperation addFieldOp = addFieldBuilder.build(); + ProjectionOperation projectOp = (new ProjectionOperation()).andInclude(new String[]{"from", "to", "usage"}).and("_id").as("deviceUuid").andExclude(new String[]{"_id"}); + return this.mongoTemplate.aggregate(Aggregation.newAggregation(new AggregationOperation[]{matchOp, sortOp, groupOp, addFieldOp, projectOp}), DataUsage.class, DataUsage.class).getMappedResults(); + } + } + + @Async + public void generateDeviceReport(User user, Site site, DbObject settings, int timeOffset, boolean mailMe) { + UUID fileUuid = UUID.randomUUID(); + UUID siteUuid = site.getUuid(); + File file = this.getReportTemplate("devices.general.xlsx"); + if (file.exists() && file.isFile()) { + try { + Collection devices = null; + String scope; + switch (settings.getString("groupOption", "all")) { + case "all": + devices = this.getDevicesForReport(siteUuid, (List)null); + scope = "All devices"; + break; + case "selected": + devices = this.getDevicesForReport(siteUuid, settings.getList("groups", UUID.class)); + scope = "Devices in the selected groups"; + break; + case "unassigned": + devices = this.getDevicesForReport(siteUuid, new ArrayList()); + scope = "Devices not in any group"; + break; + default: + scope = "Unknown"; + } + + if (devices == null) { + devices = new ArrayList(); + } + + List deviceUuids = (List)devices.stream().map(GeneralProfile::getUuid).collect(Collectors.toList()); + ExcelWriter writer = new ExcelWriter(file); + int diffHour = -timeOffset / 60; + String nowDateWithUtc = McDateTimeUtils.toString(DateTime.now(DateTimeZone.forOffsetHours(diffHour)), "yyyy-MM-dd HH:mm z"); + + for(int i = 0; i < writer.getNumberOfSheets(); ++i) { + writer.setActive(i); + writer.setCell("B3", user.getName()); + writer.setCell("B4", user.getEmail()); + writer.setCell("B5", nowDateWithUtc); + writer.setCell("B6", site.getName()); + writer.setCell("B7", scope); + } + + writer.setActive("General"); + int headerRowIndex = 9; + int rowNum = headerRowIndex + 1; + CellStyle cellStyle = writer.getCellStyle(rowNum, 0); + cellStyle.setWrapText(true); + cellStyle.setAlignment(HorizontalAlignment.LEFT); + cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + cellStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("General")); + XSSFFont defaultFont = writer.getFont(cellStyle); + XSSFFont redFont = writer.getFont(cellStyle, "red"); + XSSFRichTextString richTextAttention = new XSSFRichTextString(); + richTextAttention.append("• Device OFFLINE\n• Last seen (>45 days ago)\n• Enrolment (enabled) = FALSE", defaultFont); + if (this.hostLicenseService.isStandalone()) { + writer.removeColumns(13, 16); + } else { + richTextAttention.append("\n• License expired", defaultFont); + richTextAttention.append("\n• Days until expiration (<45 days)", defaultFont); + richTextAttention.append("\n• License auto renew = FALSE", defaultFont); + } + + writer.setCell("D3", richTextAttention); + if (!site.isStandardWithBatteryPro()) { + writer.removeColumns(4, 4); + } + + int lastColIndex = writer.getLastColIndex(headerRowIndex); + DateTime now = DateTime.now(DateTimeZone.forOffsetHours(diffHour)); + + for(Device device : devices) { + this.setGenericDeviceInfo(writer, rowNum, cellStyle, timeOffset, device); + int i = 4; + if (site.isStandardWithBatteryPro()) { + writer.setCell(rowNum, i++, device.getBatteryCondition().name(), cellStyle); + } + + boolean isEnabled = device.getEnabled(); + writer.setCell(rowNum, i++, isEnabled, cellStyle, (String)null, (String)null, (String)null, isEnabled ? null : "red"); + if (device.isEnrolled()) { + Date date = (new DateTime(device.getEnrolled())).minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, date, cellStyle, "yyyy-MM-dd", (String)null, (String)null, (String)null); + } else { + writer.setCell(rowNum, i++, "-", cellStyle); + } + + DbObject softwareInfo = device.getProfileCategory(new String[]{"software_info"}); + DbObject hardwareInfo = device.getProfileCategory(new String[]{"hardware_info"}); + writer.setCell(rowNum, i++, hardwareInfo.getString("model", "-"), cellStyle); + String deviceId = device.getDeviceId(); + writer.setCell(rowNum, i++, deviceId == null ? "-" : deviceId, cellStyle); + String productModel = hardwareInfo.getString("product_model", "-"); + writer.setCell(rowNum, i++, productModel, cellStyle); + Object osVersion = softwareInfo.get("os_version"); + writer.setCell(rowNum, i++, osVersion == null ? "-" : String.valueOf(osVersion), cellStyle); + boolean gmsAvailable = softwareInfo.getBoolean("gms_available", false); + writer.setCell(rowNum, i++, gmsAvailable, cellStyle); + writer.setCell(rowNum, i++, softwareInfo.getString("build_no", "-"), cellStyle); + writer.setCell(rowNum, i++, softwareInfo.getString("region_version", "-"), cellStyle); + if (!this.hostLicenseService.isStandalone()) { + if (device.getLicense() != null) { + DeviceLicense license = device.getLicense(); + writer.setCell(rowNum, i++, license.getLicenseModel() == null ? "-" : license.getLicenseModel().getName(), cellStyle); + boolean autoRenew = license.isAutoRenew(); + writer.setCell(rowNum, i++, autoRenew, cellStyle, (String)null, (String)null, (String)null, autoRenew ? null : "red"); + DateTime expiry = new DateTime(device.getLicenseExpiry()); + boolean isExpired = expiry.isBefore(now); + boolean isExpiring = expiry.isBefore(now.plusDays(45)); + Date date = expiry.minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, date, cellStyle, "yyyy-MM-dd", (String)null, (String)null, isExpired ? "red" : null); + int leftDays = Days.daysBetween(now, expiry).getDays(); + writer.setCell(rowNum, i++, leftDays > 0 ? leftDays : "-", cellStyle, leftDays > 0 ? "#,##0\" days\"" : null, "right", (String)null, !isExpired && isExpiring ? "red" : null); + } else { + writer.fill(rowNum, rowNum, i, i + 4, "-", cellStyle); + i += 4; + } + } + + writer.setCell(rowNum, i++, device.getOwnerInfo("name", "-"), cellStyle); + writer.setCell(rowNum, i++, device.getOwnerInfo("email", "-"), cellStyle); + writer.setCell(rowNum, i++, device.getOwnerInfo("phone", "-"), cellStyle); + writer.setCell(rowNum, i++, device.getOwnerInfo("mobile", "-"), cellStyle); + List notes = this.deviceService.getRecentNotes(device.getUuid()); + StringJoiner noteJoiner = new StringJoiner("\n"); + + for(DeviceNote note : notes) { + noteJoiner.add(note.getNote()); + } + + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(noteJoiner.toString()) ? "-" : noteJoiner.toString(), cellStyle); + ++rowNum; + } + + writer.setAutoSizeColumns(0, lastColIndex); + writer.setAutoFilter(9); + this.writeDeviceDistribution(writer, cellStyle, "Distribution", 8, devices); + writer.setActive("Network"); + DbObject usageSetting = settings.getDbObject(new String[]{"dataUsage"}); + String usageOption = usageSetting.getString("option", "both"); + boolean wifiUsage = usageOption.equals("both") || usageOption.equals("wifi"); + boolean mobileUsage = usageOption.equals("both") || usageOption.equals("mobile"); + if (!wifiUsage) { + writer.removeColumns(8, 10); + } + + if (!mobileUsage) { + writer.removeColumns(18 - (wifiUsage ? 0 : 3), 20 - (wifiUsage ? 0 : 3)); + } + + String usagePeriod = usageSetting.getString("period", "last30Days"); + DateTime today = now.withTimeAtStartOfDay(); + DateTime from; + DateTime to; + switch (usagePeriod) { + case "today": + from = today; + to = now; + break; + case "thisWeek": + from = today.withDayOfWeek(0); + to = now; + break; + case "thisMonth": + from = today.withDayOfMonth(1); + to = now; + break; + case "yesterday": + to = today; + from = today.minusDays(1); + break; + case "lastWeek": + to = today.withDayOfWeek(0); + from = to.minusDays(7); + break; + case "last24Hours": + to = now; + from = now.minusHours(24); + break; + case "last7Days": + to = today; + from = today.minusDays(7); + break; + case "ranged": + from = new DateTime(McDateTimeUtils.parseDate(usageSetting.getString("from"), (String)null)); + to = (new DateTime(McDateTimeUtils.parseDate(usageSetting.getString("to"), (String)null))).plusDays(1); + break; + case "last30Days": + default: + to = today; + from = today.minusDays(30); + } + + List dataUsages = this.getDataUsages(deviceUuids, wifiUsage, mobileUsage, from.toDate(), to.toDate()); + Map dataUsageMap = (Map)dataUsages.stream().collect(Collectors.toMap((ex) -> ex.getDeviceUuid(), (ex) -> ex)); + headerRowIndex = 9; + rowNum = headerRowIndex + 1; + lastColIndex = writer.getLastColIndex(headerRowIndex); + + for(Device device : devices) { + this.setGenericDeviceInfo(writer, rowNum, cellStyle, timeOffset, device); + int i = 4; + DbObject network = device.getProfileCategory(new String[]{"network"}); + DbObject active = network == null ? null : network.getDbObject(new String[]{"active"}); + if (device.isOnline() && active != null) { + String networkType = active.getString("type", "unknown"); + writer.setCell(rowNum, i++, networkType, cellStyle); + } else { + writer.setCell(rowNum, i++, "-", cellStyle); + } + + DbObject wifi = network == null ? null : network.getDbObject(new String[]{"wifi"}); + if (wifi != null) { + writer.setCell(rowNum, i++, wifi.getBoolean("enabled", false), cellStyle); + String ssid = wifi.getString("ssid", "-"); + if (Strings.isNullOrEmpty(ssid) || ssid.equals("unknown_ssid")) { + ssid = "-"; + } + + writer.setCell(rowNum, i++, ssid, cellStyle); + String ipAddr = wifi.getString("ip_address", "-"); + if (Strings.isNullOrEmpty(ipAddr) || ipAddr.equals("0.0.0.0")) { + ipAddr = "-"; + } + + writer.setCell(rowNum, i++, ipAddr, cellStyle); + writer.setCell(rowNum, i++, wifi.getString("mac_address", "-"), cellStyle); + } else { + writer.fill(rowNum, rowNum, i, i + 4, "-", cellStyle); + i += 4; + } + + if (wifiUsage) { + if (dataUsageMap.containsKey(device.getUuid())) { + DataUsage dataUsage = (DataUsage)dataUsageMap.get(device.getUuid()); + long size = dataUsage.getUsage("wifi", "total"); + if (size > 0L) { + Date fromTime = (new DateTime(dataUsage.getFrom())).minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, fromTime, cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, (String)null); + Date toTime = (new DateTime(dataUsage.getTo())).minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, toTime, cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, (String)null); + writer.setFileSizeCell(rowNum, i++, size, cellStyle); + } else { + writer.fill(rowNum, rowNum, i, i + 3, "-", cellStyle); + i += 3; + } + } else { + writer.fill(rowNum, rowNum, i, i + 3, "-", cellStyle); + i += 3; + } + } + + DbObject telephony = network == null ? null : network.getDbObject(new String[]{"telephony"}); + if (telephony != null && telephony.containsKey("imei") && !McStringUtils.isNullOrEmpty(telephony.getString("imei", (String)null))) { + String simState = telephony.getString("sim_state", "UNKNOWN"); + boolean isSimReady = simState.equalsIgnoreCase("READY"); + if (!isSimReady) { + writer.fill(rowNum, rowNum, i, i + 6, "-", cellStyle); + i += 6; + } else { + writer.setCell(rowNum, i++, simState, cellStyle, (String)null, (String)null, (String)null, !isSimReady ? "red" : null); + boolean dataEnabled = telephony.getBoolean("data_enabled", false); + writer.setCell(rowNum, i++, dataEnabled, cellStyle, (String)null, (String)null, (String)null, !dataEnabled ? "red" : null); + boolean dataRoamingEnabled = telephony.getBoolean("data_roaming_enabled", false); + writer.setCell(rowNum, i++, dataRoamingEnabled, cellStyle, (String)null, (String)null, (String)null, !dataRoamingEnabled ? "red" : null); + writer.setCell(rowNum, i++, telephony.getString("carrier", "-"), cellStyle); + String valueUnknown = "unknown".toUpperCase(); + String networkType = telephony.getString("network_type", valueUnknown); + String phoneType = telephony.getString("phone_type", valueUnknown); + String connectType = "unknown".toUpperCase(); + if (networkType.equals(valueUnknown) && !phoneType.equals(valueUnknown)) { + connectType = phoneType; + } else if (phoneType.equals(valueUnknown) && !networkType.equals(valueUnknown)) { + connectType = networkType; + } else if (!networkType.equals(valueUnknown) && !phoneType.equals(valueUnknown)) { + connectType = MessageFormat.format("{0} ({1})", networkType, phoneType); + } + + writer.setCell(rowNum, i++, connectType, cellStyle); + writer.setCell(rowNum, i++, telephony.getString("phone_number", telephony.getString("number", "-")), cellStyle); + } + + writer.setCell(rowNum, i++, telephony.getString("imei", "-"), cellStyle); + writer.setCell(rowNum, i++, telephony.getString("device_id", "-"), cellStyle); + } else { + writer.fill(rowNum, rowNum, i, i + 8, "-", cellStyle); + i += 8; + } + + if (mobileUsage) { + if (dataUsageMap.containsKey(device.getUuid())) { + DataUsage dataUsage = (DataUsage)dataUsageMap.get(device.getUuid()); + long size = dataUsage.getUsage("mobile", "total"); + if (size > 0L) { + Date fromTime = (new DateTime(dataUsage.getFrom())).minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, fromTime, cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, (String)null); + Date toTime = (new DateTime(dataUsage.getTo())).minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, toTime, cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, (String)null); + writer.setFileSizeCell(rowNum, i++, size, cellStyle); + } else { + writer.fill(rowNum, rowNum, i, i + 3, "-", cellStyle); + i += 3; + } + } else { + writer.fill(rowNum, rowNum, i, i + 3, "-", cellStyle); + i += 3; + } + } + + DbObject blueTooth = network == null ? null : network.getDbObject(new String[]{"bluetooth"}); + if (blueTooth != null) { + writer.setCell(rowNum, i++, blueTooth.getBoolean("enabled", false), cellStyle); + writer.setCell(rowNum, i++, blueTooth.getString("name", "-"), cellStyle); + writer.setCell(rowNum, i++, blueTooth.getString("mac_address", "-"), cellStyle); + } else { + writer.fill(rowNum, rowNum, i, i + 3, "-", cellStyle); + } + + ++rowNum; + } + + writer.setAutoSizeColumns(0, lastColIndex); + writer.setAutoFilter(9); + writer.setActive("Installed Apps"); + Document installedApps = this.installedApps(siteUuid); + Collection installedPackages = null; + switch (settings.getString("appOption", "all")) { + case "all": + if (!groupOption.equals("all") && devices.size() <= 1000) { + installedPackages = this.installedPackages(deviceUuids); + break; + } + + installedPackages = new ArrayList(installedApps.keySet()); + break; + case "selected": + installedPackages = settings.getList("apps", String.class); + break; + default: + installedPackages = new ArrayList(); + } + + List mitacPackages = new ArrayList(Arrays.asList("com.mitac.midm.client", "com.mitac.midm.system")); + Map packageIndexMap = new HashMap(); + Iterator itPackages = installedPackages.iterator(); + + while(itPackages.hasNext()) { + String packageName = (String)itPackages.next(); + if (packageName.toLowerCase().contains("mitac")) { + if (!mitacPackages.contains(packageName)) { + mitacPackages.add(packageName); + } + + itPackages.remove(); + } + } + + int installedAppIndex = 6; + int headerRow = 8; + int subHeaderRow = 9; + Cell headerCell = writer.getCell(headerRow, installedAppIndex); + CellStyle headerCellStyle = headerCell.getCellStyle(); + CellStyle subHeaderStyle = writer.getCell(subHeaderRow, installedAppIndex).getCellStyle(); + subHeaderStyle.setWrapText(true); + int colIndex = installedAppIndex; + if (!mitacPackages.isEmpty()) { + writer.merge(headerRow, headerRow, installedAppIndex, installedAppIndex + mitacPackages.size() - 1); + writer.setCell(headerCell, "MiTAC Apps", headerCellStyle); + + for(String packageName : mitacPackages) { + writer.getCell(headerRow, colIndex).setCellStyle(headerCellStyle); + String label; + if (installedApps.containsKey(packageName)) { + label = String.format("%s%n(%s)", installedApps.getString(packageName), packageName); + } else { + label = packageName; + } + + writer.setCell(writer.getCell(subHeaderRow, colIndex++), label, subHeaderStyle); + packageIndexMap.put(packageName, packageIndexMap.size()); + } + } + + installedPackages = (Collection)installedPackages.stream().sorted().collect(Collectors.toList()); + if (!installedPackages.isEmpty()) { + writer.merge(headerRow, headerRow, colIndex, colIndex + installedPackages.size() - 1); + headerCell = writer.getCell(headerRow, colIndex); + writer.setCell(headerCell, "Other Apps", headerCellStyle); + colIndex = colIndex; + + for(String packageName : installedPackages) { + writer.getCell(headerRow, colIndex).setCellStyle(headerCellStyle); + String label; + if (installedApps.containsKey(packageName)) { + label = String.format("%s%n(%s)", installedApps.getString(packageName), packageName); + } else { + label = packageName; + } + + writer.setCell(writer.getCell(subHeaderRow, colIndex++), label, subHeaderStyle); + packageIndexMap.put(packageName, packageIndexMap.size()); + } + } else { + writer.removeColumns(colIndex, colIndex); + } + + headerRowIndex = 9; + rowNum = headerRowIndex + 1; + lastColIndex = writer.getLastColIndex(headerRowIndex); + + for(Device device : devices) { + this.setGenericDeviceInfo(writer, rowNum, cellStyle, timeOffset, device); + int i = 4; + List profiles = this.profileService.profileStatesByDevice(device); + if (profiles.isEmpty()) { + writer.setCell(rowNum, i++, "-", cellStyle); + writer.setCell(rowNum, i++, "-", cellStyle); + } else { + XSSFRichTextString richTextProfile = new XSSFRichTextString(); + XSSFRichTextString richTextState = new XSSFRichTextString(); + boolean needNewLine = false; + + for(Document profile : profiles) { + if (needNewLine) { + richTextProfile.append("\n"); + richTextState.append("\n"); + } else { + needNewLine = true; + } + + String name = profile.getString("name"); + boolean isApplied = false; + if (profile.containsKey("state")) { + Document state = (Document)profile.get("state", Document.class); + String stateVal = state.getString("state"); + if (!McStringUtils.isNullOrEmpty(stateVal) && stateVal.equals("done")) { + isApplied = true; + } + } + + String state = isApplied ? McDateTimeUtils.toString(new DateTime(profile.getLong("updated")), "yyyy-MM-dd") : "Not applied"; + if (isApplied) { + richTextProfile.append(name, defaultFont); + richTextState.append(state, defaultFont); + } else { + richTextProfile.append(name, redFont); + richTextState.append(state, redFont); + } + } + + writer.setCell(rowNum, i++, richTextProfile, cellStyle); + writer.setCell(rowNum, i++, richTextState, cellStyle); + } + + List appList = device.getInstalledApps(); + i = 6; + writer.fill(rowNum, rowNum, i, i + mitacPackages.size() + installedPackages.size() - 1, "-", cellStyle); + if (appList != null) { + for(AppInfo appInfo : appList) { + if (packageIndexMap.containsKey(appInfo.getPackageName())) { + int index = (Integer)packageIndexMap.get(appInfo.getPackageName()); + writer.setCell(rowNum, i + index, appInfo.getVersionName(), cellStyle); + } + } + } + + ++rowNum; + } + + writer.setAutoSizeColumns(0, lastColIndex); + writer.setAutoFilter(9); + writer.setActive(0); + String category = "device"; + SiteFile siteReport = this.saveReport(fileUuid, user, writer, site.getIdName(), category, timeOffset); + writer.close(); + if (siteReport != null) { + this.newsMesageSerivce.sendReportMessage(user, site, category, siteReport, true, mailMe); + } else { + this.newsMesageSerivce.sendReportMessage(user, site, category, (SiteFile)null, false, mailMe); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + + private void setGenericDeviceInfo(ExcelWriter writer, int rowNum, CellStyle cellStyle, int timeOffset, Device device) { + int i = 0; + writer.setCell(rowNum, i++, device.getSerialNo(), cellStyle); + boolean isOnline = device.isOnline(); + String onlineState = isOnline ? "ONLINE" : "OFFLINE"; + writer.setCell(rowNum, i++, onlineState, cellStyle, (String)null, (String)null, (String)null, isOnline ? null : "red"); + if (!isOnline && device.getLastDisconnected() != null) { + DateTime lastDisconnected = new DateTime(device.getLastDisconnected()); + boolean isTooLongAgo = lastDisconnected.isBefore(DateTime.now().minusDays(45)); + Date date = lastDisconnected.minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, date, cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, isTooLongAgo ? "red" : null); + } else { + writer.setCell(rowNum, i++, "-", cellStyle); + } + + String deviceGroupPath = device.getGroupPath(); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(deviceGroupPath) ? "-" : deviceGroupPath, cellStyle); + } + + @Async + public void generateProfileReport(User user, Site site, DbObject settings, int timeOffset, boolean mailMe) { + String category = "profile"; + UUID fileUuid = UUID.randomUUID(); + UUID siteUuid = site.getUuid(); + File file = this.getReportTemplate("profiles.general.xlsx"); + if (file.exists() && file.isFile()) { + try { + ExcelWriter writer = new ExcelWriter(file); + String scope; + List deviceProfiles; + switch (settings.getString("groupOption", "all")) { + case "all": + scope = "All profiles"; + deviceProfiles = this.profileService.findAllWithGroupPathAndAppliedQtyBySiteUuid(siteUuid, (List)null); + break; + case "selected": + deviceProfiles = this.profileService.findAllWithGroupPathAndAppliedQtyBySiteUuid(siteUuid, settings.getList("groups", UUID.class)); + scope = "Profiles in the selected groups"; + break; + case "unassigned": + deviceProfiles = this.profileService.findAllWithGroupPathAndAppliedQtyBySiteUuid(siteUuid, new ArrayList()); + scope = "Profiles not in any group"; + break; + default: + scope = "Unknown"; + deviceProfiles = new ArrayList(); + } + + int diffHour = -timeOffset / 60; + String nowDateWithUtc = McDateTimeUtils.toString(DateTime.now(DateTimeZone.forOffsetHours(diffHour)), "yyyy-MM-dd HH:mm z"); + writer.setCell("B3", user.getName()); + writer.setCell("B4", user.getEmail()); + writer.setCell("B5", nowDateWithUtc); + writer.setCell("B6", site.getName()); + writer.setCell("B7", scope); + int rowNum = 10; + CellStyle cellStyle = writer.getCellStyle(rowNum, 0); + cellStyle.setWrapText(true); + cellStyle.setAlignment(HorizontalAlignment.LEFT); + cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + cellStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("General")); + Set installUuids = new HashSet(); + deviceProfiles.forEach((profilex) -> { + profilex.initApps(); + List uuids = profilex.getInstallUuids(); + if (uuids != null && !uuids.isEmpty()) { + installUuids.addAll(uuids); + } + + }); + int headerRowIndex = 8; + int subHeaderRowIndex = 9; + int appIndex = 11; + Collection appFiles = this.fileService.findApps(installUuids, (String)null, Integer.MAX_VALUE); + List mitacPackages = new ArrayList(Arrays.asList("com.mitac.midm.client", "com.mitac.midm.system")); + List otherPackages = new ArrayList(); + Map appPackageMap = new HashMap(); + Map appUuidMap = new HashMap(); + if (appFiles != null && !appFiles.isEmpty()) { + boolean midmClientExists = false; + boolean midmSystemExists = false; + + for(AppFile appFile : appFiles) { + appUuidMap.put(appFile.getFileUuid(), appFile); + String packageName = appFile.getPackageName(); + if (!appPackageMap.containsKey(packageName)) { + appPackageMap.put(packageName, appFile); + } + + if (appFile.isMitacApp()) { + if (packageName.equals("com.mitac.midm.client")) { + midmClientExists = true; + } + + if (packageName.equals("com.mitac.midm.system")) { + midmSystemExists = true; + } + + if (!mitacPackages.contains(packageName)) { + mitacPackages.add(packageName); + } + } else if (!otherPackages.contains(packageName)) { + otherPackages.add(packageName); + } + } + + if (!midmSystemExists) { + mitacPackages.remove(1); + } + + if (!midmClientExists) { + mitacPackages.remove(0); + } + + Cell headerCell = writer.getCell(headerRowIndex, appIndex); + CellStyle headerCellStyle = headerCell.getCellStyle(); + CellStyle subHeaderStyle = writer.getCell(subHeaderRowIndex, appIndex).getCellStyle(); + subHeaderStyle.setWrapText(true); + int shiftColumnNumber = appPackageMap.size() - 1; + writer.insertColumns(appIndex + 1, shiftColumnNumber); + writer.merge(headerRowIndex, headerRowIndex, appIndex, appIndex + (mitacPackages.isEmpty() ? 0 : mitacPackages.size() - 1), headerCellStyle); + writer.setCell(headerRowIndex, appIndex, "MiTAC Apps", headerCellStyle); + + for(String packageName : mitacPackages) { + AppFile appInfo = (AppFile)appPackageMap.get(packageName); + String label = appInfo == null ? "-" : String.format("%s%n(%s)", appInfo.getLabel(), packageName); + writer.setCell(headerRowIndex + 1, appIndex++, label, subHeaderStyle); + } + + if (!otherPackages.isEmpty()) { + writer.merge(headerRowIndex, headerRowIndex, appIndex, appIndex + otherPackages.size() - 1, headerCellStyle); + writer.setCell(headerRowIndex, appIndex, "Other Apps", headerCellStyle); + + for(String packageName : otherPackages) { + AppFile appInfo = (AppFile)appPackageMap.get(packageName); + String label = appInfo == null ? "-" : String.format("%s%n(%s)", appInfo.getLabel(), packageName); + writer.setCell(headerRowIndex + 1, appIndex++, label, subHeaderStyle); + } + } + } else { + writer.removeColumns(appIndex, appIndex); + } + + int lastColIndex = writer.getLastColIndex(subHeaderRowIndex); + + for(DeviceProfile deviceProfile : deviceProfiles) { + int i = 0; + DbObject profile = deviceProfile.getProfile(); + writer.setCell(rowNum, i++, deviceProfile.getProfile().get("name"), cellStyle); + String profileGroupPath = profile.getString("groupPath"); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(profileGroupPath) ? "-" : profileGroupPath, cellStyle); + writer.setCell(rowNum, i++, deviceProfile.getEnabled(), cellStyle); + if (deviceProfile.getUpdated() != null) { + Date date = (new DateTime(deviceProfile.getUpdated())).minusMinutes(timeOffset).toDate(); + writer.setCell(rowNum, i++, date, cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, (String)null); + } else { + writer.setCell(rowNum, i++, "-", cellStyle); + } + + writer.setCell(rowNum, i++, deviceProfile.isGlobal(), cellStyle); + if (deviceProfile.isGlobal()) { + writer.setCell(rowNum, i++, "", cellStyle); + } else { + List scopeGroupNames = profile.getList("scopeGroupNames", String.class); + StringJoiner scopeGroupNameJoiner = new StringJoiner("\n"); + if (scopeGroupNames != null) { + for(String name : scopeGroupNames) { + if (!Strings.isNullOrEmpty(name)) { + scopeGroupNameJoiner.add(name); + } + } + } + + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(scopeGroupNameJoiner.toString()) ? "-" : scopeGroupNameJoiner.toString(), cellStyle); + } + + Integer deviceQty = profile.getInteger("deviceQty"); + Integer appliedQty = profile.getInteger("appliedQty"); + if (appliedQty == -1) { + appliedQty = 0; + } + + writer.setCell(rowNum, i++, deviceQty, cellStyle); + writer.setCell(rowNum, i++, appliedQty, cellStyle); + writer.setCell(rowNum, i++, deviceQty - appliedQty, cellStyle); + StringJoiner baseImgJoiner = new StringJoiner("\n"); + StringJoiner regionImgJoiner = new StringJoiner("\n"); + List otaUuids = deviceProfile.getOtas(); + if (otaUuids != null && !otaUuids.isEmpty()) { + List otas = this.fileService.findOtas(otaUuids); + if (otas != null) { + for(OtaFile ota : otas) { + if (otas != null && !Strings.isNullOrEmpty(ota.getDisplayId())) { + if (ota.isSystemImage()) { + String displayId = ota.getDisplayId(); + if (ota.isPartial()) { + displayId = String.format("%s => %s", ota.getPreDisplayId(), displayId); + } + + baseImgJoiner.add(displayId); + } else { + regionImgJoiner.add(ota.getReleaseVersion()); + } + } + } + } + } + + writer.setCell(rowNum, i++, baseImgJoiner.length() == 0 ? "-" : baseImgJoiner.toString(), cellStyle); + writer.setCell(rowNum, i++, regionImgJoiner.length() == 0 ? "-" : regionImgJoiner.toString(), cellStyle); + if (!appPackageMap.isEmpty()) { + writer.fill(rowNum, rowNum, i, i + appPackageMap.size() - 1, "-", cellStyle); + List installApps = deviceProfile.getInstallApps(); + if (installApps != null && !installApps.isEmpty()) { + for(ProfileApps.InstallApp app : installApps) { + AppFile appFile = (AppFile)appUuidMap.get(app.getUuid()); + if (appFile != null) { + String packageName = appFile.getPackageName(); + String versionName = appFile.getVersionName(); + int index = mitacPackages.indexOf(packageName); + if (index < 0) { + index = mitacPackages.size() + otherPackages.indexOf(packageName); + } + + writer.setCell(rowNum, i + index, Strings.isNullOrEmpty(packageName) ? "-" : versionName, cellStyle); + } + } + } + + i += appPackageMap.size(); + } + + String applyOrder = (String)deviceProfile.getProfile("applyOrder", "-"); + writer.setCell(rowNum, i++, applyOrder.equals("none") ? "-" : applyOrder, cellStyle); + writer.setCell(rowNum, i++, deviceProfile.getProfile("updateVia", "both"), cellStyle); + DbObject profileObj = deviceProfile.getProfile(); + Object startsOnDate = deviceProfile.getProfile("startsOn", deviceProfile.getCreated()); + String dateStr; + if (startsOnDate instanceof Date) { + dateStr = McDateTimeUtils.toString(new DateTime(startsOnDate), "yyyy-MM-dd"); + } else if (startsOnDate instanceof String) { + dateStr = (String)startsOnDate; + } else { + dateStr = "-"; + } + + writer.setCell(rowNum, i++, dateStr, cellStyle); + String endsOption = profileObj.getString("endsOption", "never"); + String endsDate = profileObj.getString("ends"); + if (!endsOption.equals("never") && endsDate != null) { + writer.setCell(rowNum, i++, endsDate, cellStyle); + } else { + writer.setCell(rowNum, i++, "Never", cellStyle); + } + + String repeatOption = ""; + JsonElement jProfile = McJsonUtils.toJsonElement(deviceProfile.getProfile()); + JsonObject jProfileObject = jProfile.getAsJsonObject(); + if (jProfileObject.get("repeatOption") != null && !String.valueOf(jProfileObject.get("repeatOption")).replace("\"", "").equalsIgnoreCase("once")) { + String period = jProfileObject.get("repeatPeriod").getAsString(); + if (period.equals("week")) { + List dayList = new ArrayList(); + JsonArray weekAry = jProfileObject.getAsJsonArray("weekOptions"); + if (weekAry != null && !weekAry.isEmpty()) { + weekAry.forEach((day) -> dayList.add(day.getAsString().substring(0, 1))); + JsonElement var115 = jProfileObject.get("repeatOption"); + repeatOption = var115 + " day " + String.join(",", dayList) + " in a week"; + } else { + repeatOption = "Every week but not select yet"; + } + } else if (period.equals("month")) { + List dayList = new ArrayList(); + JsonObject obj = jProfileObject.getAsJsonObject("monthOptions"); + if (obj.get("first") != null && obj.get("first").getAsBoolean()) { + dayList.add("first"); + } + + if (obj.get("last") != null && obj.get("last").getAsBoolean()) { + dayList.add("last"); + } + + JsonArray dayAry = obj.getAsJsonArray("days"); + if (dayAry != null) { + dayAry.forEach((day) -> dayList.add(day.getAsString().replace(".0", ""))); + } + + if (!dayList.isEmpty()) { + JsonElement var10000 = jProfileObject.get("repeatOption"); + repeatOption = var10000 + " day " + String.join(",", dayList) + " in a month"; + } else { + repeatOption = "Every month but not select yet"; + } + } else { + JsonElement var114 = jProfileObject.get("repeatOption"); + repeatOption = var114 + " " + jProfileObject.get("repeatEvery") + " " + jProfileObject.get("repeatPeriod"); + } + } else { + repeatOption = "once"; + } + + writer.setCell(rowNum, i++, repeatOption.replace("\"", ""), cellStyle); + String startTime = ""; + String finishTime = ""; + StringJoiner scheduleJoiner = new StringJoiner("\n"); + if (deviceProfile.getProfile().get("timeOption") != null && !deviceProfile.getProfile().get("timeOption").toString().trim().replace("\"", "").equals("allDay") && jProfileObject.has("applicableTimes")) { + JsonArray jApplicableTime = jProfileObject.get("applicableTimes").getAsJsonArray(); + + for(int idx = 0; idx < jApplicableTime.size(); ++idx) { + JsonObject jObject = jApplicableTime.get(idx).getAsJsonObject(); + if (idx % 2 == 0) { + startTime = jObject.get("time").getAsString(); + } else { + finishTime = jObject.get("time").getAsString(); + scheduleJoiner.add(startTime + "-" + finishTime); + } + } + } + + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(scheduleJoiner.toString()) ? "-" : scheduleJoiner.toString(), cellStyle); + ++rowNum; + } + + writer.setAutoSizeColumns(0, lastColIndex); + writer.setAutoFilter(9); + SiteFile siteReport = this.saveReport(fileUuid, user, writer, site.getIdName(), category, timeOffset); + if (siteReport != null) { + this.newsMesageSerivce.sendReportMessage(user, site, category, siteReport, true, mailMe); + return; + } + + this.newsMesageSerivce.sendReportMessage(user, site, category, (SiteFile)null, false, mailMe); + } catch (Exception e) { + e.printStackTrace(); + } + } + + this.newsMesageSerivce.sendReportMessage(user, site, category, (SiteFile)null, false, mailMe); + } + + @Async + public void generateSiteReport(User user, Site userSite, Site detailSite, int timeOffset, DbObject itemSettings, boolean mailMe) { + File file = this.getReportTemplate("site.general.xlsx"); + if (file.exists() && file.isFile()) { + String category = "site"; + if (detailSite == null) { + detailSite = userSite; + } else { + category = category + "_" + detailSite.getName().replaceAll(" ", "_"); + } + + try { + ExcelWriter writer = new ExcelWriter(file); + if (itemSettings != null) { + Map.of("orders", "License orders", "inventory", "License inventory", "valid", "Valid licenses", "expired", "Expired licenses", "issued", "Issued licenses").forEach((key, sheetName) -> { + if (this.hostLicenseService.isStandalone() || !itemSettings.getBoolean(key, true)) { + writer.removeSheet(new String[]{sheetName}); + } + + }); + } + + int diffHour = -timeOffset / 60; + String nowDateWithUtc = McDateTimeUtils.toString(DateTime.now(DateTimeZone.forOffsetHours(diffHour)), "yyyy-MM-dd HH:mm z"); + int rowNum = 0; + + for(int i = 0; i < writer.getNumberOfSheets(); ++i) { + writer.setActive(i); + rowNum = 3; + writer.setCell(String.format("B%s", rowNum++), user.getName()); + writer.setCell(String.format("B%s", rowNum++), user.getEmail()); + writer.setCell(String.format("B%s", rowNum++), nowDateWithUtc); + writer.setCell(String.format("B%s", rowNum++), userSite.getName()); + } + + writer.setActive("General"); + rowNum = 9; + writer.setCell(String.format("B%s", rowNum++), detailSite.getIdName()); + writer.setCell(String.format("B%s", rowNum++), detailSite.getName()); + writer.setCell(String.format("B%s", rowNum++), detailSite.getPlanName()); + writer.setCell(String.format("B%s", rowNum++), String.valueOf(this.deviceService.getDeviceCount(detailSite.getUuid()))); + writer.setCell(String.format("B%s", rowNum++), String.valueOf(this.siteLicenseService.getValidLicenseCount(detailSite))); + writer.setCell(String.format("B%s", rowNum++), detailSite.getEnabled()); + writer.setCell(String.format("B%s", rowNum++), detailSite.getCreated() == null ? "-" : McDateTimeUtils.toString(new DateTime(detailSite.getCreated(), DateTimeZone.forOffsetHours(diffHour)), "yyyy-MM-dd HH:mm z")); + writer.setCell(String.format("B%s", rowNum++), detailSite.getUpdated() == null ? "-" : McDateTimeUtils.toString(new DateTime(detailSite.getUpdated(), DateTimeZone.forOffsetHours(diffHour)), "yyyy-MM-dd HH:mm z")); + writer.setCell(String.format("B%s", rowNum++), Strings.isNullOrEmpty(detailSite.getAddress()) ? "-" : detailSite.getAddress()); + writer.setCell(String.format("B%s", rowNum++), Strings.isNullOrEmpty(detailSite.getPhone()) ? "-" : detailSite.getPhone()); + rowNum = 21; + CellStyle cellStyle = writer.getCellStyle(rowNum, 0); + cellStyle.setWrapText(true); + cellStyle.setAlignment(HorizontalAlignment.LEFT); + cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + cellStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("General")); + CellStyle dateStyle = writer.newCellStyle(); + dateStyle.cloneStyleFrom(cellStyle); + dateStyle.setDataFormat(writer.getCreationHelper().createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss")); + + for(User supervisor : this.userService.findSupervisors(detailSite.getUuid())) { + int j = 0; + writer.setCell(rowNum, j++, supervisor.getName(), cellStyle); + writer.setCell(rowNum, j++, supervisor.getEmail(), cellStyle); + String phone = (String)supervisor.getProfile("phone"); + writer.setCell(rowNum, j++, Strings.isNullOrEmpty(phone) ? "-" : phone, cellStyle); + ++rowNum; + } + + writer.setAutoSizeColumns(0, writer.getLastColIndex(23)); + if (detailSite.isReseller() && !this.hostLicenseService.isStandalone()) { + writer.setActive("Child sites"); + rowNum = 8; + if (this.hostLicenseService.isStandalone()) { + writer.removeColumns(4, 4); + } + + List siteList = new ArrayList(); + siteList.addAll(this.siteService.findAll(userSite, (String)null, (String)null, (String)null, true)); + + for(Site site : siteList) { + int i = 0; + this.siteService.updateLatestVisit(site); + Page users = this.userService.findSupervisors(site.getUuid(), (String)null, 0, 2, "sites.created", "asc"); + StringJoiner supVisorNameJoiner = new StringJoiner("\n"); + StringJoiner supVisorEmailJoiner = new StringJoiner("\n"); + StringJoiner supVisorPhoneJoiner = new StringJoiner("\n"); + + for(User supervisor : users.getContent()) { + supVisorNameJoiner.add(supervisor.getName()); + supVisorEmailJoiner.add(supervisor.getEmail()); + String phone = (String)supervisor.getProfile("phone"); + supVisorPhoneJoiner.add(Strings.isNullOrEmpty(phone) ? "-" : phone); + } + + writer.setCell(rowNum, i++, site.getIdName(), cellStyle); + writer.setCell(rowNum, i++, site.getName(), cellStyle); + writer.setCell(rowNum, i++, site.getPlanName(), cellStyle); + long deviceCount = this.deviceService.getDeviceCount(site.getUuid()); + writer.setCell(rowNum, i++, deviceCount, cellStyle); + if (!this.hostLicenseService.isStandalone()) { + long validLicenses = (long)this.siteLicenseService.getValidLicenseCount(site); + writer.setCell(rowNum, i++, validLicenses, cellStyle, (String)null, (String)null, (String)null, deviceCount > validLicenses ? "red" : null); + } + + writer.setCell(rowNum, i++, site.getEnabled(), cellStyle); + writer.setCell(rowNum, i++, site.getCreated() == null ? "-" : site.getCreated(), dateStyle); + writer.setCell(rowNum, i++, site.getLatestVisit() == null ? "-" : site.getLatestVisit(), dateStyle); + String supervirsorNames = supVisorNameJoiner.toString(); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(supervirsorNames) ? "-" : supervirsorNames, cellStyle); + String supervirsorEmails = supVisorEmailJoiner.toString(); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(supervirsorEmails) ? "-" : supervirsorEmails, cellStyle); + String supVisorPhones = supVisorPhoneJoiner.toString(); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(supVisorPhones) ? "-" : supVisorPhones, cellStyle); + ++rowNum; + } + + if (rowNum >= 10) { + writer.setCell(rowNum, 2, "Total :", cellStyle); + writer.setSumToCells(rowNum, this.hostLicenseService.isStandalone() ? new String[]{"D"} : new String[]{"D", "E"}, 9, rowNum, cellStyle, "right"); + } + + writer.setAutoSizeColumns(0, writer.getLastColIndex(7)); + writer.setAutoFilter(7); + } else { + writer.removeSheet(new String[]{"Child sites"}); + } + + this.writeDeviceDistribution(writer, cellStyle, "Device distribution", 11, this.getDevicesForReport(detailSite.getUuid(), (List)null)); + if (!this.hostLicenseService.isStandalone()) { + this.writeLicenseSheets(writer, detailSite, userSite, cellStyle); + } + + writer.setActive("Device distribution"); + + for(int i = writer.getActiveSheetIndex(); i < writer.getNumberOfSheets(); ++i) { + writer.setActive(i); + rowNum = 9; + writer.setCell(String.format("B%s", rowNum++), detailSite.getIdName()); + writer.setCell(String.format("B%s", rowNum++), detailSite.getName()); + } + + writer.setActive(0); + SiteFile siteReport = this.saveReport(UUID.randomUUID(), user, writer, userSite.getIdName(), category, timeOffset); + if (siteReport != null) { + this.newsMesageSerivce.sendReportMessage(user, userSite, category, siteReport, true, mailMe); + } else { + this.newsMesageSerivce.sendReportMessage(user, userSite, category, (SiteFile)null, false, mailMe); + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + } + + private void writeLicenseSheets(ExcelWriter writer, Site site, Site userSite, CellStyle cellStyle) { + if (writer.setActive("License orders")) { + int rowNum = 13; + + for(SiteLicense siteLicense : this.siteLicenseService.find(site, false, (JsonObject)null, "created", Direction.ASC)) { + int i = 0; + DbObject ref = siteLicense.getReference(); + LicenseModel licenseModel = siteLicense.getLicenseModel(); + String po = ref == null ? null : ref.getString("po"); + DbObject report = siteLicense.getReport(); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(po) ? "-" : po, cellStyle); + writer.setCell(rowNum, i++, siteLicense.getPlan() == null ? "-" : siteLicense.getPlan(), cellStyle); + writer.setCell(rowNum, i++, licenseModel == null ? "-" : licenseModel.getName(), cellStyle); + writer.setCell(rowNum, i++, siteLicense.getStatus().toString(), cellStyle); + writer.setCell(rowNum, i++, siteLicense.getUpdated(), cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, (String)null); + writer.setCell(rowNum, i++, siteLicense.getAmount(), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("fresh", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("active", 0) + report.getInteger("inactive", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("used", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("licensed", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("expired", 0), cellStyle); + ++rowNum; + } + + if (rowNum >= 17) { + writer.setCell(rowNum, 4, "Total :", cellStyle); + writer.setSumToCells(rowNum, new String[]{"F", "G", "H", "I", "J", "K"}, 14, rowNum, cellStyle, "right"); + } + + writer.setAutoFilter(12); + } + + if (writer.setActive("License inventory")) { + int rowNum = 13; + + for(LicenseModel licenseModel : this.siteLicenseService.getLicenseModels(site)) { + int i = 0; + DbObject report = licenseModel.getReport(); + writer.setCell(rowNum, i++, licenseModel.getName(), cellStyle); + writer.setCell(rowNum, i++, report.getString("plan"), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("total", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("fresh", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("active", 0) + report.getInteger("inactive", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("used", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("licensed", 0), cellStyle); + int expired = report.getInteger("expired", 0); + writer.setCell(rowNum, i++, expired, cellStyle); + int expiredIn45 = report.getInteger("expiredIn45", 0) - expired; + writer.setCell(rowNum, i++, expiredIn45, cellStyle, (String)null, (String)null, (String)null, expiredIn45 > 0 ? "red" : null); + int expiredIn45WithAutoRenew = report.getInteger("expiredIn45WithAutoRenew", 0); + writer.setCell(rowNum, i++, expiredIn45WithAutoRenew, cellStyle); + int autoRenewValid = report.getInteger("fresh", 0) + report.getInteger("used", 0); + writer.setCell(rowNum, i++, autoRenewValid, cellStyle, (String)null, (String)null, (String)null, autoRenewValid < expiredIn45WithAutoRenew ? "red" : null); + ++rowNum; + } + + writer.setAutoFilter(12); + } + + DateTime dayAfter45 = DateTime.now().plusDays(45); + + for(String sheetName : new String[]{"Valid licenses", "Expired licenses"}) { + if (writer.setActive(sheetName)) { + boolean forValid = sheetName.equals("Valid licenses"); + int rowNum = 12; + + CloseableIterator licenseStream; + for(licenseStream = this.queryLicensesFor(site, forValid); licenseStream.hasNext(); ++rowNum) { + DeviceLicense license = (DeviceLicense)licenseStream.next(); + String po = license.getPo(); + LicenseModel licenseModel = license.getLicenseModel(); + String serialNo = license.getDeviceSerial(); + int activationCount = license.getActivationCount(); + String licenseStatus = null; + if (serialNo == null) { + licenseStatus = activationCount == 0 ? "fresh" : "used"; + } else { + licenseStatus = "assigned"; + } + + int i = 0; + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(po) ? "-" : po, cellStyle); + writer.setCell(rowNum, i++, licenseModel == null ? "-" : licenseModel.getName(), cellStyle); + writer.setCell(rowNum, i++, license.getPlan(), cellStyle); + writer.setCell(rowNum, i++, license.getUuid().toString(), cellStyle); + writer.setCell(rowNum, i++, licenseStatus, cellStyle); + if (license.getActivatedAt() == null) { + writer.setCell(rowNum, i++, "-", cellStyle); + } else { + writer.setCell(rowNum, i++, license.getActivatedAt(), cellStyle, "yyyy-MM-dd HH:mm:ss", (String)null, (String)null, (String)null); + } + + Date licenseExpiry = license.getExpiry(); + boolean isSoon = forValid && licenseExpiry != null && dayAfter45.isAfter(licenseExpiry.getTime()); + writer.setCell(rowNum, i++, licenseExpiry, cellStyle, "yyyy-MM-dd", (String)null, (String)null, isSoon ? "red" : null); + writer.setCell(rowNum, i++, activationCount >= 2 ? 2 : activationCount, cellStyle, (String)null, (String)null, (String)null, activationCount >= 2 ? "red" : null); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(serialNo) ? "-" : serialNo, cellStyle); + } + + licenseStream.close(); + writer.setAutoFilter(11); + } + } + + if (site.isReseller() && !this.hostLicenseService.isStandalone() && writer.setActive("Issued licenses")) { + int rowNum = 13; + int size = 100; + int page = 0; + Page siteLicenses = this.siteLicenseService.find(userSite, true, (JsonObject)null, page, size, "created", Direction.DESC); + int totalPage = siteLicenses.getTotalPages(); + + while(totalPage > page) { + for(SiteLicense siteLicense : siteLicenses) { + int i = 0; + writer.setCell(rowNum, i++, siteLicense.getChildSite() == null ? "-" : siteLicense.getChildSite().getName(), cellStyle); + DbObject ref = siteLicense.getReference(); + String po = ref == null ? null : ref.getString("po"); + writer.setCell(rowNum, i++, Strings.isNullOrEmpty(po) ? "-" : po, cellStyle); + LicenseModel licenseModel = siteLicense.getLicenseModel(); + writer.setCell(rowNum, i++, licenseModel == null ? "-" : licenseModel.getName(), cellStyle); + writer.setCell(rowNum, i++, siteLicense.getPlan(), cellStyle); + writer.setCell(rowNum, i++, siteLicense.getStatus().toString(), cellStyle); + writer.setCell(rowNum, i++, siteLicense.getUpdated(), cellStyle, "yyyy-MM-dd", (String)null, (String)null, (String)null); + DbObject report = siteLicense.getReport(); + writer.setCell(rowNum, i++, siteLicense.getAmount(), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("fresh", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("active", 0) + report.getInteger("inactive", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("used", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("licensed", 0), cellStyle); + writer.setCell(rowNum, i++, report.getInteger("expired", 0), cellStyle); + Document doc = this.siteLicenseService.getExpiringCount(siteLicense.getUuid(), new Date()); + List objList = doc.getList("nearestExpired", Document.class); + Object nearestExpired = objList.isEmpty() ? "-" : ((Document)objList.get(0)).getDate("_id"); + writer.setCell(rowNum, i++, nearestExpired, cellStyle, "yyyy-MM-dd", (String)null, (String)null, (String)null); + writer.setCell(rowNum, i++, objList.isEmpty() ? "-" : ((Document)objList.get(0)).getInteger("count"), cellStyle); + objList = doc.getList("upcomingExpiration", Document.class); + Date upcomingExpiration = objList.isEmpty() ? null : ((Document)objList.get(0)).getDate("_id"); + boolean isSoon = upcomingExpiration != null && dayAfter45.isAfter(upcomingExpiration.getTime()); + String upcomingColor = isSoon ? "red" : null; + writer.setCell(rowNum, i++, upcomingExpiration == null ? "-" : upcomingExpiration, cellStyle, "yyyy-MM-dd", (String)null, (String)null, upcomingColor); + writer.setCell(rowNum, i++, objList.isEmpty() ? "-" : ((Document)objList.get(0)).getInteger("count"), cellStyle, (String)null, (String)null, (String)null, upcomingColor); + ++rowNum; + } + + ++page; + if (totalPage > page) { + siteLicenses = this.siteLicenseService.find(userSite, true, (JsonObject)null, page, size, "created", Direction.DESC); + } + } + + writer.setAutoFilter(12); + } else { + writer.removeSheet(new String[]{"Issued licenses"}); + } + + } + + private CloseableIterator queryLicensesFor(Site site, boolean forValid) { + Date now = new Date(); + List criterias = new ArrayList(); + if (site.isChild()) { + criterias.add(Criteria.where("site.$id").is(site.getReseller().getUuid()).and("childSite.$id").is(site.getUuid())); + } else { + criterias.add(Criteria.where("site.$id").is(site.getUuid()).and("childSite").exists(false)); + } + + if (forValid) { + criterias.add((new Criteria()).orOperator(new Criteria[]{Criteria.where("expiry").gt(now), Criteria.where("expiry").exists(false)})); + } else { + criterias.add(Criteria.where("expiry").lte(now)); + } + + Query query = Query.query((new Criteria()).andOperator(criterias)); + query.with(Sort.by(forValid ? Direction.ASC : Direction.DESC, new String[]{"expiry"})); + return this.mongoTemplate.stream(query, DeviceLicense.class); + } + + private SiteFile saveReport(UUID fileUuid, User user, ExcelWriter writer, String siteName, String category, int offsetMins) { + try { + if (fileUuid == null) { + fileUuid = UUID.randomUUID(); + } + + String filePath = this.getFilePath(user.getSiteUuid(), "report", fileUuid); + McFile targetFile = new McFile(filePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + OutputStream fos = new FileOutputStream(new File(filePath)); + writer.write(fos); + fos.flush(); + fos.close(); + SiteFile siteReport = null; + if (targetFile.exists()) { + String name = siteReport == null ? null : siteReport.getName(); + siteReport = new SiteFile(user, fileUuid, targetFile); + String fileName = String.format("%s_%s_%s.xlsx", siteName, category, this.getDateTimeStr(offsetMins)); + if (siteReport.getLength() > 0L) { + siteReport.setSiteUuid(user.getSiteUuid()); + siteReport.setSiteName(siteName); + siteReport.setFileName(fileName); + siteReport.setName(Strings.isNullOrEmpty(name) ? fileName : name); + siteReport.setType(targetFile.getContentType()); + siteReport.setLastModified(targetFile.lastModified()); + siteReport.setRequestedFrom(user); + siteReport.setCategory(category); + siteReport.setRequested(new Date()); + siteReport.setExpiry((new DateTime()).plusWeeks(1).toLocalDate().toDate()); + this.save(siteReport); + return siteReport; + } + + targetFile.delete(); + return null; + } + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + private void writeDeviceDistribution(ExcelWriter writer, CellStyle cellStyle, String sheetName, int headerRowIndex, Collection devices) { + writer.setActive(sheetName); + if (this.hostLicenseService.isStandalone()) { + writer.removeColumns(6, 7); + } + + int lastColIndex = writer.getLastColIndex(headerRowIndex); + int startRow = headerRowIndex + 1; + int rowNum = startRow; + Map> devGroupMap = new HashMap(); + + for(Device device : devices) { + DeviceGrouping dg = new DeviceGrouping(device); + if (!devGroupMap.containsKey(dg)) { + devGroupMap.put(dg, dg.isExpired() ? Pair.of(0, 1) : Pair.of(1, 0)); + } else { + Pair pair = (Pair)devGroupMap.get(dg); + devGroupMap.put(dg, dg.isExpired() ? Pair.of((Integer)pair.getFirst(), (Integer)pair.getSecond() + 1) : Pair.of((Integer)pair.getFirst() + 1, (Integer)pair.getSecond())); + } + } + + List groupings = new ArrayList(devGroupMap.keySet()); + if (!groupings.isEmpty()) { + groupings.sort((a, b) -> a.getHashKey().compareToIgnoreCase(b.getHashKey())); + + for(DeviceGrouping grouping : groupings) { + int i = 0; + writer.setCell(rowNum, i++, grouping.getDeviceId(), cellStyle); + writer.setCell(rowNum, i++, grouping.getProductModel(), cellStyle); + writer.setCell(rowNum, i++, grouping.getProductId(), cellStyle); + writer.setCell(rowNum, i++, grouping.getOsVersion(), cellStyle); + writer.setCell(rowNum, i++, grouping.isGmsAvailable(), cellStyle); + Pair pair = (Pair)devGroupMap.get(grouping); + int activeQty = (Integer)pair.getFirst(); + int inactiveQty = (Integer)pair.getSecond(); + int deviceQty = activeQty + inactiveQty; + writer.setCell(rowNum, i++, deviceQty, cellStyle); + if (!this.hostLicenseService.isStandalone()) { + writer.setCell(rowNum, i++, activeQty, cellStyle, (String)null, (String)null, (String)null, activeQty < inactiveQty ? "red" : null); + writer.setCell(rowNum, i++, inactiveQty, cellStyle, (String)null, (String)null, (String)null, inactiveQty > 0 ? "red" : null); + } + + ++rowNum; + } + } + + if (rowNum > startRow) { + writer.setCell(rowNum, 4, "Total :", cellStyle); + writer.setSumToCells(rowNum, this.hostLicenseService.isStandalone() ? new String[]{"F"} : new String[]{"F", "G", "H"}, startRow + 1, startRow + groupings.size(), cellStyle, "right"); + } + + writer.setAutoSizeColumns(0, lastColIndex); + writer.setAutoFilter(headerRowIndex); + } + + public String getTemplateFilePath(String fileName) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "report", new Object[]{fileName}); + } + + @Scheduled( + cron = "0 10 0 * * *" + ) + public void expireReport() { + if (this.hostLicenseService.isPrimaryServer()) { + this.taskExecutor.submit(new Runnable() { + public void run() { + Query query = Query.query(Criteria.where("expiry").lt(LocalDate.now().toDate())); + List siteReports = ReportService.this.mongoTemplate.find(query, SiteFile.class); + if (!siteReports.isEmpty()) { + siteReports.forEach((siteReport) -> { + McFile targetFile = null; + if (siteReport.getCategory().equals("device_file_pull")) { + targetFile = new McFile(ReportService.this.getDeviceFilePath(siteReport.getSiteUuid(), UUID.fromString(siteReport.getFileInfo().get("deviceUuid").toString()), siteReport.getFileUuid())); + } else { + targetFile = new McFile(ReportService.this.getFilePath(siteReport.getSiteUuid(), "report", siteReport.getFileUuid())); + } + + if (targetFile.exists()) { + targetFile.delete(); + } + + }); + ReportService.this.mongoTemplate.remove(query, SiteFile.class); + } + + } + }); + } + } + + private class DeviceGrouping { + private final Device device; + private final String hashKey; + private final DbObject hardwareInfo; + private final DbObject softwareInfo; + + protected DeviceGrouping(Device device) { + this.device = device; + this.hardwareInfo = device.getProfileCategory(new String[]{"hardware_info"}); + this.softwareInfo = device.getProfileCategory(new String[]{"software_info"}); + this.hashKey = String.format("%s%s%s%s%s", this.getDeviceId(), this.getProductModel(), this.getProductId(), this.getOsVersion(), this.isGmsAvailable()); + if (!ReportService.hashesMap.containsKey(this.hashKey)) { + ReportService.hashesMap.put(this.hashKey, ReportService.hashesMap.size()); + } + + } + + protected String getDeviceId() { + return this.device.isEnrolled() ? this.device.getDeviceId() : "unknown"; + } + + protected String getProductId() { + return this.device.isEnrolled() ? this.hardwareInfo.getString("product_id", "-") : "-"; + } + + protected String getProductModel() { + return this.device.isEnrolled() ? this.hardwareInfo.getString("model", this.getProductId()) : "-"; + } + + protected String getOsVersion() { + return this.device.isEnrolled() ? this.softwareInfo.getString("os_version", "-") : "-"; + } + + protected boolean isGmsAvailable() { + return this.softwareInfo.getBoolean("gms_available", false); + } + + protected boolean isExpired() { + return !ReportService.this.hostLicenseService.isStandalone() && this.device.isLicenseExpired(); + } + + protected String getHashKey() { + return this.hashKey; + } + + public int hashCode() { + return (Integer)ReportService.hashesMap.get(this.hashKey); + } + + public boolean equals(Object obj) { + return this.hashCode() == ((DeviceGrouping)obj).hashCode(); + } + } +} diff --git a/src/main/java/com/midm/service/log/LogService.java b/src/main/java/com/midm/service/log/LogService.java new file mode 100644 index 0000000..f96ae0f --- /dev/null +++ b/src/main/java/com/midm/service/log/LogService.java @@ -0,0 +1,265 @@ +package com.midm.service.log; + +import com.google.common.base.Strings; +import com.midm.constant.LocaleConst; +import com.midm.model.log.MidmLog; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.service.BaseService; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.DeleteResult; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +/** + * ====================================================================================== + * 全局审计与操作日志核心服务 (LogService) + * ====================================================================================== + * + *

【架构设计与高可用亮点】 + * 1. 业务价值: + * - 满足企业安全合规要求,记录管理员的操作记录(用户登录、许可分配、策略下发) + * 以及终端设备的运行事件(设备注册、OTA固件升级、网络切换、应用安装)。 + * 2. 【高并发幂等性设计 (Idempotent Logging)】: + * - 面对移动网络环境频繁抖动、TCP重传、设备端重试机制可能导致的重复日志报文, + * 在 {@link #save(MidmLog)} 中采用 MongoDB 的 `$setOnInsert` 结合复合索引: + * `Query(forWhat + category + loggedAt)` + `mongoTemplate.upsert(...)`。 + * - 只有当不存在完全相同的日志记录时才执行插入,若重复上报则直接被原子级忽略, + * 从数据库引擎层面保证了日志上报的严格幂等。 + * 3. 动态复杂过滤与归档清理: + * - 支持按租户、事件类型、时间范围多维分页查询,并提供针对设备销毁时的关联日志级联清理接口。 + * + * @author MiDM Core Platform Team + */ +@Service +public class LogService extends BaseService { + + /** + * 记录管理员后台操作日志 + * + * @param user 执行操作的用户实体 + * @param logFor 关联操作对象 UUID(如设备 UUID、企业租户 UUID 或策略 UUID) + * @param category 日志分类(如 "device", "policy", "license", "auth") + * @param log 日志详细描述文本 + */ + public void save(User user, UUID logFor, String category, String log) { + MidmLog midmLog = new MidmLog(user, logFor, category, log); + this.save(midmLog); + } + + /** + * 记录受控终端设备事件日志(不带附加元数据) + * + * @param deviceUuid 设备全局唯一标识 + * @param category 分类(如 "event", "network", "system") + * @param log 日志内容 + * @param loggedAt 终端设备本地发生的时间戳 + */ + public void saveDeviceLog(UUID deviceUuid, String category, String log, Date loggedAt) { + this.saveDeviceLog(deviceUuid, category, log, loggedAt, (String)null, (Object)null); + } + + /** + * 记录受控终端设备事件日志(带扩展参考键值对引用) + * + * @param deviceUuid 设备全局唯一标识 + * @param category 分类 + * @param log 日志描述 + * @param loggedAt 发生时间 + * @param refKey 扩展数据键(如 "otaVersion", "appPackage", "errorCode") + * @param reference 扩展数据实体或对象 + */ + public void saveDeviceLog(UUID deviceUuid, String category, String log, Date loggedAt, String refKey, Object reference) { + MidmLog midmLog = new MidmLog((User)null, deviceUuid, category, log); + if (reference != null) { + midmLog.addReference(refKey, reference); + } + if (loggedAt != null) { + midmLog.setLoggedAt(loggedAt); + } + this.save(midmLog); + } + + /** + * 【核心实现:幂等日志存储】 + * + *

利用 MongoDB upsert + $setOnInsert 确保弱网重传场景下日志记录的唯一性与幂等性。 + * + * @param log 待保存的日志模型 + */ + public void save(MidmLog log) { + // 构建联合去重匹配条件:对象ID + 分类 + 原始记录发生时间 + Query query = new Query(Criteria.where("forWhat").is(log.getForWhat()) + .and("category").is(log.getCategory()) + .and("loggedAt").is(log.getLoggedAt())); + + // 仅在文档不存在触发新增时才写入字段($setOnInsert) + Update update = (new Update()) + .setOnInsert("uuid", log.getUuid()) + .setOnInsert("forWhat", log.getForWhat()) + .setOnInsert("category", log.getCategory()) + .setOnInsert("log", log.getLog()) + .setOnInsert("loggedAt", log.getLoggedAt()); + + if (log.getLogger() != null) { + update.setOnInsert("logger", log.getLogger()); + } + if (log.hasReference()) { + update.setOnInsert("reference", log.getReference()); + } + + try { + this.mongoTemplate.upsert(query, update, MidmLog.class); + } catch (Exception var5) { + // 吞掉偶发并发重复插入产生的异常,确保上游通信链路不被中断 + } + } + + /** + * 批量直接插入日志集合(常用于历史日志同步或批量导入) + */ + public Collection save(Collection logs) { + return this.mongoTemplate.insert(logs, MidmLog.class); + } + + /** + * 校验完全相同日志内容与时间点的记录是否已存在 + */ + public boolean exists(MidmLog log) { + Query query = Query.query(Criteria.where("log").is(log.getLog()).and("loggedAt").is(log.getLoggedAt())); + return this.mongoTemplate.exists(query, MidmLog.class); + } + + /** + * 动态多条件通用分页日志检索 + * + * @param filter JSON 格式动态过滤条件 + * @param page 页码 + * @param size 单页数量 + * @param sortBy 排序字段(默认按 loggedAt) + * @param direction 升序/降序(默认 desc) + * @return 分页结果 + */ + public Page findLogs(String filter, Integer page, Integer size, String sortBy, String direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "loggedAt"; + direction = "desc"; + } + + Criteria criteria = McMongoUtils.toCriteria(filter); + Query query = new Query(criteria); + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, MidmLog.class); + if (total < (long)(size * (page + 1)) && ((float)total * 1.0F / (float)size <= (float)page || (float)total * 1.0F / (float)size > (float)(page + 1))) { + page = 0; + } + + Sort sort = Sort.by(McMongoUtils.toDirection(direction), new String[]{sortBy}); + query.with(sort); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), MidmLog.class); + return new PageImpl(result, pageable, total); + } + + /** + * 查询企业租户最近的 License 授权流转动态 + */ + public List findLinceseActivities(Site site, int limit, boolean forManagement) { + Query query = new Query(); + Criteria criteria = Criteria.where("forWhat").is(site.getUuid()).and("category").is("license"); + if (forManagement) { + criteria.orOperator(new Criteria[]{Criteria.where("reference.activity").is("add"), Criteria.where("reference.activity").is("assign")}); + } + + query.addCriteria(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"loggedAt"})); + query.limit(limit); + return this.mongoTemplate.find(query, MidmLog.class); + } + + /** + * 分页查询 License 操作历史日志 + */ + public Page findLinceseLogs(Site site, String category, Integer page, Integer size, String sortBy, String direction, boolean forManagement) { + Query query = new Query(); + Criteria criteria = Criteria.where("forWhat").is(site.getUuid()).and("category").is("license"); + if (forManagement) { + if (Strings.isNullOrEmpty(category)) { + criteria.orOperator(new Criteria[]{Criteria.where("reference.activity").is("add"), Criteria.where("reference.activity").is("assign")}); + } else { + criteria.and("reference.activity").is(category); + } + } else if (!Strings.isNullOrEmpty(category)) { + criteria.and("reference.activity").is(category); + } + + query.addCriteria(criteria); + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, MidmLog.class); + Sort sort = Strings.isNullOrEmpty(sortBy) ? Sort.by(Direction.DESC, new String[]{"loggedAt"}) : Sort.by(McMongoUtils.toDirection(direction), new String[]{sortBy}); + query.with(sort); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), MidmLog.class); + return new PageImpl(result, pageable, total); + } + + /** + * 清除租户下的 License 审计日志 + */ + public long clearLinceseLogs(Site site, String category, boolean forManagement) { + Query query = new Query(); + Criteria criteria = Criteria.where("forWhat").is(site.getUuid()).and("category").is("license"); + if (forManagement) { + if (Strings.isNullOrEmpty(category)) { + criteria.orOperator(new Criteria[]{Criteria.where("reference.activity").is("add"), Criteria.where("reference.activity").is("assign")}); + } else { + criteria.and("reference.activity").is(category); + } + } else if (!Strings.isNullOrEmpty(category)) { + criteria.and("reference.activity").is(category); + } + + query.addCriteria(criteria); + DeleteResult deleteResult = this.mongoTemplate.remove(query, MidmLog.class); + return deleteResult.getDeletedCount(); + } + + /** + * 删除单条日志 + */ + public boolean delete(MidmLog log) { + return this.deleteById(MidmLog.class, log.getUuid()); + } + + /** + * 批量根据主键 ID 物理删除日志 + */ + public DeleteResult delete(List uuids) { + Query query = Query.query(Criteria.where("_id").in(uuids)); + return this.mongoTemplate.remove(query, MidmLog.class); + } + + /** + * 清理指定对象关联的所有历史日志(如设备报废出库时的数据注销脱敏) + * + * @param uuid 关联目标对象主键 + * @return 实际清除的条目数 + */ + public long clearAllLogsFor(UUID uuid) { + Query query = Query.query(Criteria.where("forWhat").is(uuid)); + return this.mongoTemplate.remove(query, MidmLog.class).getDeletedCount(); + } +} diff --git a/src/main/java/com/midm/service/message/MidmWebSocketSession.java b/src/main/java/com/midm/service/message/MidmWebSocketSession.java new file mode 100644 index 0000000..c684570 --- /dev/null +++ b/src/main/java/com/midm/service/message/MidmWebSocketSession.java @@ -0,0 +1,410 @@ +package com.midm.service.message; + +import com.google.common.base.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.model.IF_EXISTS_OPTION; +import com.midm.model.device.Device; +import com.midm.model.file.AppFile; +import com.midm.model.message.MIDM_REQUEST; +import com.midm.model.message.MidmPacket; +import com.midm.model.org.User; +import com.mitac.cell.internet.http.McHttpClient; +import com.mitac.cell.net.McNetUtils; +import com.mitac.cell.utils.McBooleanUtils; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.joda.time.DateTime; +import org.springframework.http.HttpHeaders; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.PingMessage; +import org.springframework.web.socket.PongMessage; +import org.springframework.web.socket.WebSocketMessage; +import org.springframework.web.socket.WebSocketSession; + +public class MidmWebSocketSession { + public static final WebSocketMessage pingMessage = new PingMessage(); + public static final WebSocketMessage pongMessage = new PongMessage(); + private int heartbeatTimeout; + private final WebSocketSession session; + private final HttpHeaders headers; + private String jSessionId; + private Object holder; + private DateTime pongTimeStamp; + private DateTime dataUsageCheckedAt; + private ScheduledExecutorService scheduledExecutorService; + private ScheduledFuture futureHeartbeatCheckTask; + private ScheduledFuture futurePingCheckTask; + private Runnable pongCheckTask; + private Runnable heartbeatCheckTask; + + public MidmWebSocketSession(WebSocketSession session) { + this.heartbeatTimeout = 70; + this.pongTimeStamp = DateTime.now(); + this.dataUsageCheckedAt = DateTime.now(); + this.pongCheckTask = new Runnable() { + public void run() { + MidmWebSocketSession.this.close(CloseStatus.SESSION_NOT_RELIABLE); + } + }; + this.heartbeatCheckTask = new Runnable() { + public void run() { + MidmWebSocketSession.this.ping(); + } + }; + this.session = session; + this.headers = session.getHandshakeHeaders(); + List cookies = this.getHeaders("Cookie"); + if (cookies != null && !cookies.isEmpty()) { + for(String cookieValue : cookies) { + String jSessionId = McHttpClient.getCookieValue(cookieValue, "JSESSIONID"); + if (!Strings.isNullOrEmpty(jSessionId)) { + this.jSessionId = jSessionId; + break; + } + } + } + + } + + public MidmWebSocketSession(WebSocketSession session, int heartbeatInterval) { + this(session); + this.setHeartbeatInterval(heartbeatInterval); + } + + public void setHeartbeatInterval(int heartbeatInterval) { + this.heartbeatTimeout = heartbeatInterval + 10; + } + + public String getJSessionId() { + return this.jSessionId; + } + + public UUID getSiteUuid() { + if (this.holder != null) { + return this.isUser() ? this.getUser().getSiteUuid() : this.getDevice().getSiteUuid(); + } else { + String siteUuid = this.getHeader("siteUuid"); + + try { + return Strings.isNullOrEmpty(siteUuid) ? null : UUID.fromString(siteUuid); + } catch (Exception var3) { + return null; + } + } + } + + public WebSocketSession getWebSocketSession() { + return this.session; + } + + public Principal getPrincipal() { + return this.session.getPrincipal(); + } + + public boolean isOpen() { + return this.session.isOpen(); + } + + public String sessionId() { + return this.session.getId(); + } + + public boolean isFrom(String from) { + return from.equals(this.from()); + } + + public String from() { + List headers = this.getHeaders("from"); + return headers != null && !headers.isEmpty() ? (String)headers.get(0) : null; + } + + public String getRemoteIpAddress() { + String ip = this.getHeader("X-Forwarded-For"); + if (!Strings.isNullOrEmpty(ip)) { + return ip; + } else { + ip = this.getHeader("X-Real-IP"); + if (!Strings.isNullOrEmpty(ip)) { + return ip; + } else { + return this.session == null ? null : McNetUtils.ipAddress(this.session.getRemoteAddress().getAddress()); + } + } + } + + public String getIpAddress() { + return this.getHeader("ip_addr"); + } + + public String serialNo() { + return this.getHeader("serialNo"); + } + + public String timeZone() { + return this.getHeader("timeZone"); + } + + public String encryptString() { + return this.getHeader("encryptString"); + } + + public boolean rtcEnabled() { + return this.headers.containsKey("rtcEnabled"); + } + + public boolean hasSiteUuid() { + return this.headers.containsKey("siteUuid"); + } + + public UUID groupUuid() { + String value = this.getHeader("groupUuid"); + return value == null ? null : UUID.fromString(value); + } + + public String owner() { + String value = this.getHeader("owner"); + JsonElement json = McJsonUtils.toJsonElement(value); + if (json == null) { + return null; + } else if (json.isJsonPrimitive()) { + return json.getAsString(); + } else if (json.isJsonObject()) { + JsonElement jEmail = json.getAsJsonObject().get("email"); + return jEmail != null ? jEmail.getAsString() : null; + } else { + return null; + } + } + + public void setHolder(Object holder) { + this.holder = holder; + } + + public Device getDevice() { + return this.isDevice() ? (Device)this.holder : null; + } + + public User getUser() { + return this.isUser() ? (User)this.holder : null; + } + + public boolean isDevice() { + return this.holder instanceof Device; + } + + public boolean isUser() { + return this.holder instanceof User; + } + + public String getId() { + return this.getWebSocketSession().getId(); + } + + public UUID getUuid() { + if (this.holder != null) { + if (this.holder instanceof Device) { + return ((Device)this.holder).getUuid(); + } + + if (this.holder instanceof User) { + return ((User)this.holder).getUuid(); + } + } + + return null; + } + + public boolean selfEnroll() { + String value = this.getHeader("selfEnroll"); + return value == null ? false : McBooleanUtils.isTrue(value); + } + + public IF_EXISTS_OPTION ifExistsOption() { + String value = this.getHeader("ifExists"); + return value == null ? IF_EXISTS_OPTION.skip : IF_EXISTS_OPTION.get(value); + } + + public String licenseId() { + return this.getHeader("license"); + } + + public Boolean autoRenew() { + String value = this.getHeader("renew"); + return McBooleanUtils.isTrue(value); + } + + public Boolean renewToSameModel() { + String value = this.getHeader("renewToSameModel"); + return McBooleanUtils.isTrue(value); + } + + public int clientVersion() { + String value = this.getHeader("clientVersion"); + + try { + return !Strings.isNullOrEmpty(value) ? Integer.parseInt(value) : -1; + } catch (Exception var3) { + return -1; + } + } + + public void sendRequest(int code) { + MidmPacket packet = new MidmPacket(code); + this.sendPacket(packet); + } + + public void sendRequest(MIDM_REQUEST request) { + MidmPacket packet = new MidmPacket(request.getCode()); + this.sendPacket(packet); + } + + public void sendEnrollRequest(Device device) { + MidmPacket packet = new MidmPacket(MIDM_REQUEST.ENROLL); + packet.getQuery().setRequest("enroll"); + packet.getQuery().setParam("siteUuid", device.getSiteUuid()); + packet.getQuery().setParam("deviceUuid", device.getUuid()); + this.sendPacket(packet); + } + + public void sendClientUpdateRequest(Device device, AppFile app) { + MidmPacket packet = new MidmPacket(MIDM_REQUEST.COMMAND); + packet.setRecieverUuid(device.getUuid()); + packet.getQuery().setRequest("apps"); + packet.setParam("command", "install"); + JsonObject jParams = new JsonObject(); + UUID var10000 = device.getSiteUuid(); + String url = var10000 + "/file/app/" + app.getFileUuid() + "/" + app.getFileName(); + jParams.addProperty("url", url); + McJsonUtils.setProperty(jParams, "data", app); + jParams.addProperty("remove_after_install", true); + packet.setParam("params", jParams); + this.sendPacket(packet); + } + + public void sendFeedback(int code) { + this.sendFeedback(code, "", (Object)null); + } + + public void sendFeedback(int code, String message, Object data) { + MidmPacket packet = new MidmPacket(); + packet.setFeedback(code, message, data); + this.sendPacket(packet); + } + + public boolean sendPacket(MidmPacket packet) { + return this.sendMessage((WebSocketMessage)packet.toBinary()); + } + + public boolean sendMessage(MidmPacket packet) { + return this.sendMessage((WebSocketMessage)packet.toMessage()); + } + + public boolean sendMessage(WebSocketMessage message) { + try { + synchronized(this.session) { + if (this.session.isOpen()) { + this.session.sendMessage(message); + if (this.isDevice() && !(message instanceof PingMessage) && !(message instanceof PongMessage)) { + this.ping(); + } + } + } + + return true; + } catch (Exception var5) { + return false; + } + } + + public void scheduleTocheckHeartbeat() { + this.cancelFutureTask(this.futureHeartbeatCheckTask); + this.validateScheduleExcutorService(); + this.futureHeartbeatCheckTask = this.scheduledExecutorService.schedule(this.heartbeatCheckTask, (long)this.heartbeatTimeout, TimeUnit.SECONDS); + } + + public void ping() { + if (!(new DateTime()).minusSeconds(this.heartbeatTimeout > 120 ? 120 : this.heartbeatTimeout).isBefore(this.pongTimeStamp)) { + this.cancelFutureTask(this.futurePingCheckTask); + this.sendMessage(pingMessage); + this.validateScheduleExcutorService(); + this.futurePingCheckTask = this.scheduledExecutorService.schedule(this.pongCheckTask, 30L, TimeUnit.SECONDS); + } + + } + + public void pong() { + this.sendMessage(pongMessage); + } + + public void onPong() { + this.scheduleTocheckHeartbeat(); + } + + public void updatePongTimeStamp() { + this.pongTimeStamp = DateTime.now(); + this.scheduleTocheckHeartbeat(); + } + + public boolean needToUpdateDataUsage() { + if (this.isDevice() && this.dataUsageCheckedAt.isBefore(this.pongTimeStamp.minusHours(1))) { + this.dataUsageCheckedAt = this.pongTimeStamp; + return true; + } else { + return false; + } + } + + public void close(CloseStatus reason) { + try { + this.cancelFutureTask(this.futureHeartbeatCheckTask); + this.cancelFutureTask(this.futurePingCheckTask); + if (this.scheduledExecutorService != null) { + this.scheduledExecutorService.shutdown(); + } + + if (this.session != null && this.session.isOpen()) { + this.session.close(reason); + } + } catch (IOException var3) { + } + + } + + private List getHeaders(String key) { + return this.headers.get(key); + } + + private String getHeader(String key) { + return this.headers.getFirst(key); + } + + private void validateScheduleExcutorService() { + if (this.scheduledExecutorService != null) { + this.scheduledExecutorService.shutdownNow(); + } + + this.scheduledExecutorService = Executors.newScheduledThreadPool(2); + } + + private void cancelFutureTask(ScheduledFuture futureTask) { + if (futureTask != null && !futureTask.isCancelled() && !futureTask.isDone()) { + futureTask.cancel(true); + } + + } + + protected void finalize() throws Throwable { + if (this.scheduledExecutorService != null && !this.scheduledExecutorService.isShutdown()) { + this.scheduledExecutorService.shutdownNow(); + } + + } +} diff --git a/src/main/java/com/midm/service/message/UserSocketSessions.java b/src/main/java/com/midm/service/message/UserSocketSessions.java new file mode 100644 index 0000000..7e0951b --- /dev/null +++ b/src/main/java/com/midm/service/message/UserSocketSessions.java @@ -0,0 +1,45 @@ +package com.midm.service.message; + +import com.midm.model.message.MidmPacket; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.UUID; + +public class UserSocketSessions { + private String jSessionId; + private Set sessions = new HashSet(); + + public UserSocketSessions(MidmWebSocketSession session) { + this.jSessionId = session.getJSessionId(); + this.sessions.add(session); + } + + public String getjSessionId() { + return this.jSessionId; + } + + public Set getSessions() { + return this.sessions; + } + + public void add(MidmWebSocketSession session) { + this.sessions.add(session); + } + + public void remove(MidmWebSocketSession session) { + this.sessions.remove(session); + } + + public void sendMessage(UUID siteUuid, MidmPacket packetFeedback) { + Iterator it = this.sessions.iterator(); + + while(it.hasNext()) { + MidmWebSocketSession session = (MidmWebSocketSession)it.next(); + if ((siteUuid == null || siteUuid.equals(session.getSiteUuid())) && !session.sendMessage(packetFeedback)) { + it.remove(); + } + } + + } +} diff --git a/src/main/java/com/midm/service/message/WebSocketSessionManager.java b/src/main/java/com/midm/service/message/WebSocketSessionManager.java new file mode 100644 index 0000000..0afe9ae --- /dev/null +++ b/src/main/java/com/midm/service/message/WebSocketSessionManager.java @@ -0,0 +1,908 @@ +package com.midm.service.message; + +import com.google.common.base.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import com.midm.model.IF_EXISTS_OPTION; +import com.midm.model.device.AppInfo; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceLicense; +import com.midm.model.device.ReconnectMonitor; +import com.midm.model.message.MIDM_REQUEST; +import com.midm.model.message.MidmPacket; +import com.midm.model.message.MidmQuery; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.SiteLicense; +import com.midm.model.org.User; +import com.midm.security.UserPrincipal; +import com.midm.service.battery.BatteryService; +import com.midm.service.device.DeviceAppsService; +import com.midm.service.device.DeviceKeyService; +import com.midm.service.device.DeviceReportService; +import com.midm.service.device.DeviceService; +import com.midm.service.log.LogService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.internet.websocket.SocketCloseStatus; +import com.mitac.cell.utils.McJsonUtils; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import org.bson.Document; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Configurable; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.util.Pair; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.stereotype.Service; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketMessage; +import org.springframework.web.socket.WebSocketSession; + +/** + * ====================================================================================== + * 全局长连接会话生命周期与路由管理器 (WebSocketSessionManager) + * ====================================================================================== + * + *

【架构设计与高并发通信亮点】 + * 1. 核心定位: + * - 维护全网在线智能终端与 Web 管理用户的长连接会话(Session)拓扑状态机。 + * 2. 【高并发线程安全会话路由】: + * - `sessions`: SessionId -> Session(底层原生映射); + * - `userSessions`: UserUuid -> Session(Web 管理员会话映射); + * - `deviceSessions`: DeviceUuid -> Session(边缘智能终端会话映射); + * - 全量采用 {@link java.util.concurrent.ConcurrentHashMap} 实现无锁化高吞吐读写。 + * 3. 【网络防重放与恶意重连防刷机制 (ReconnectMonitor)】: + * - 实现 {@link ReconnectMonitor.OnAbusedListener} 接口; + * - 当弱网环境下边缘终端陷入高频快速重连风暴(Reconnection Storm)时,自动触发频控防刷抑制, + * 保护云端网关不被连接打垮。 + * 4. 【全双工消息路由与指令投递】: + * - 支持点对点单播(向指定终端下发锁屏/重启指令); + * - 支持按租户/分组的组播推送与状态广播; + * - 自动追踪公网 IP、局域网 IP 与设备网络接入跳跃历史。 + * + * @author MiDM Core Platform Team + */ +@Service +@Configurable +public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListener { + /** 全局活跃底层 WebSocket 会话映射表 (SessionId -> MidmWebSocketSession) */ + private Map sessions = new ConcurrentHashMap(); + + /** 在线 Web 管理用户路由表 (UserUuid -> MidmWebSocketSession) */ + private Map userSessions = new ConcurrentHashMap(); + + /** 在线边缘受控设备路由表 (DeviceUuid -> MidmWebSocketSession) */ + private Map deviceSessions = new ConcurrentHashMap(); + + /** 终端高频重连与滥用探测监控表 (DeviceUuid / SerialNo -> ReconnectMonitor) */ + private Map reconnectMonitors = new ConcurrentHashMap(); + @Autowired + @Lazy + private DeviceService deviceService; + @Autowired + @Lazy + private BatteryService batteryService; + @Autowired + @Lazy + private DeviceAppsService deviceAppsService; + @Autowired + private DeviceKeyService deviceKeyService; + @Autowired + @Lazy + private DeviceReportService deviceReportService; + @Autowired + @Lazy + private UserService userService; + @Autowired + @Lazy + private SiteService siteService; + @Autowired + private SettingsService settingsService; + @Autowired + @Lazy + private HostLicenseService hostLicenseService; + @Autowired + @Lazy + private LogService logService; + @Autowired + protected TaskScheduler taskScheduler; + + public void onConnected(MidmWebSocketSession session) { + if (this.isValid(session) && this.register(session)) { + this.saveDeviceReportAndLog(session); + } + + } + + private void saveDeviceReportAndLog(MidmWebSocketSession session) { + UUID deviceUuid = session.getUuid(); + String publicIp = session.getRemoteIpAddress(); + if (Strings.isNullOrEmpty(publicIp)) { + publicIp = "unknown"; + } + + String log = "Connected-" + publicIp; + String ipAddr = session.getIpAddress(); + Document dbObject = new Document("public_ip", publicIp); + if (!Strings.isNullOrEmpty(ipAddr)) { + dbObject.put("ip_addr", ipAddr); + log = log + "(" + ipAddr + ")"; + } + + this.deviceService.updatePublicIp(deviceUuid, ipAddr); + this.deviceReportService.save(session.getDevice(), "network", dbObject); + this.logService.save((User)null, deviceUuid, "event", log); + } + + public void onPing(MidmWebSocketSession midmSession) { + if (this.isValid(midmSession)) { + midmSession.pong(); + midmSession.onPong(); + } + + } + + public void onPong(MidmWebSocketSession midmSession) { + if (this.isValid(midmSession)) { + midmSession.onPong(); + } + + } + + private boolean isValid(MidmWebSocketSession midmSession) { + if (this.hostLicenseService.isStandalone()) { + if (!this.hostLicenseService.isValid()) { + return false; + } + } else if (midmSession.isDevice()) { + Device device = this.deviceService.validateLicense(midmSession.getDevice()); + if (device == null) { + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return false; + } + } + + return true; + } + + public boolean register(MidmWebSocketSession midmSession) { + this.sessions.put(midmSession.sessionId(), midmSession); + UUID uuid = midmSession.getUuid(); + if (midmSession.isDevice()) { + MidmWebSocketSession prevSession = (MidmWebSocketSession)this.deviceSessions.get(uuid); + if (prevSession != null && !prevSession.sessionId().equals(midmSession.sessionId())) { + this.sessions.remove(prevSession.sessionId()); + prevSession.close(CloseStatus.NORMAL); + } + + this.deviceSessions.put(uuid, midmSession); + Device device = midmSession.getDevice(); + if (this.deviceService.blockAllowed(device.getSiteUuid())) { + if (this.reconnectMonitors.containsKey(uuid)) { + ReconnectMonitor reconnectMonitor = (ReconnectMonitor)this.reconnectMonitors.get(uuid); + if (reconnectMonitor.isBlocked()) { + return false; + } + + reconnectMonitor.connected(); + } else { + this.reconnectMonitors.put(uuid, new ReconnectMonitor(device, this)); + } + } + + this.queryDeviceInfo(device.getUuid(), midmSession); + midmSession.scheduleTocheckHeartbeat(); + } else { + UserSocketSessions curUserSessions = (UserSocketSessions)this.userSessions.get(uuid); + if (curUserSessions == null) { + curUserSessions = new UserSocketSessions(midmSession); + this.userSessions.put(uuid, curUserSessions); + } else if (curUserSessions.getjSessionId().equals(midmSession.getJSessionId())) { + curUserSessions.add(midmSession); + } else { + curUserSessions.getSessions().forEach((session) -> session.close(CloseStatus.NORMAL)); + curUserSessions = new UserSocketSessions(midmSession); + this.userSessions.put(uuid, curUserSessions); + } + + User user = midmSession.getUser(); + this.logService.save(user, user.getUuid(), "event", "Connected-" + midmSession.getRemoteIpAddress()); + } + + this.sessions.put(midmSession.sessionId(), midmSession); + this.notifyOnLineStatus(midmSession, true); + return true; + } + + private void updateDeviceInfo(Device device, MidmWebSocketSession session) { + String curTimeZone = session.timeZone(); + boolean curRtcEnabled = session.rtcEnabled(); + String prevTimezone = device.getProfileCategory(new String[]{"hardware_info"}).getString("timezone"); + boolean prevRtcEnabled = device.getStates().getBoolean("rtcEnabled", false); + if (curRtcEnabled != prevRtcEnabled || curTimeZone != null && !curTimeZone.equals(prevTimezone)) { + this.deviceService.update(device.getUuid(), "profile.hardware_info.timezone", curTimeZone, "states.rtcEnabled", curRtcEnabled); + } + + } + + public void queryDeviceInfo(UUID uuid) { + if (this.deviceSessions.containsKey(uuid)) { + this.queryDeviceInfo(uuid, (MidmWebSocketSession)this.deviceSessions.get(uuid)); + } + + } + + public void queryDeviceInfo(UUID uuid, MidmWebSocketSession session) { + if (session != null) { + MidmPacket packet = new MidmPacket(); + MidmQuery query = new MidmQuery(MIDM_REQUEST.DEVICE_INFO.getCode()); + if (session.getSiteUuid() != null && this.siteService.hasBatteryPlan(session.getSiteUuid())) { + query.setParam("hasBatteryPlan", true); + } + + packet.setRecieverUuid(uuid); + packet.setQuery(query); + session.sendPacket(packet); + } + } + + public void requestDataUsage(UUID deviceUuid, DateTime from, DateTime to) { + if (this.isOnline(deviceUuid) && from.compareTo(to) < 0) { + MidmPacket packet = new MidmPacket(); + MidmQuery query = new MidmQuery(MIDM_REQUEST.QUERY.getCode()); + packet.setRecieverUuid(deviceUuid); + query.setRequest("network"); + query.setParam("command", "data_usage"); + JsonObject jParams = new JsonObject(); + jParams.addProperty("networkType", "both"); + jParams.addProperty("from", from.getMillis() + 1L); + jParams.addProperty("to", to.getMillis()); + query.setParam("params", jParams); + packet.setQuery(query); + if (this.deviceSessions.containsKey(deviceUuid)) { + ((MidmWebSocketSession)this.deviceSessions.get(deviceUuid)).sendPacket(packet); + } + } + + } + + public void onDisconnected(UUID deviceUuid, CloseStatus status) { + if (this.deviceSessions.containsKey(deviceUuid)) { + MidmWebSocketSession midmSession = (MidmWebSocketSession)this.deviceSessions.get(deviceUuid); + this.onDisconnected(midmSession.getWebSocketSession(), status); + } + + } + + public void onDisconnected(WebSocketSession session, CloseStatus status) { + MidmWebSocketSession midmSession = (MidmWebSocketSession)this.sessions.get(session.getId()); + if (midmSession != null) { + UUID uuid = midmSession.getUuid(); + String reason = SocketCloseStatus.reason(status); + if (midmSession.isDevice()) { + if (uuid != null) { + this.deviceSessions.remove(uuid); + midmSession.close(CloseStatus.SESSION_NOT_RELIABLE); + this.notifyOnLineStatus(midmSession, false); + this.logService.save((User)null, uuid, "event", String.format("Disconnected(%d: %s)", status.getCode(), reason)); + this.deviceReportService.stopProfileNotifySchedule(uuid); + } + } else { + this.userSessions.remove(uuid); + User user = midmSession.getUser(); + this.logService.save(user, user.getUuid(), "event", String.format("Disconnected(%d: %s)", status.getCode(), reason)); + } + + this.sessions.remove(session.getId()); + } + } + + public void logout(User user) { + if (user != null) { + UUID userUuid = user.getUuid(); + if (this.userSessions.containsKey(userUuid)) { + UserSocketSessions sessions = (UserSocketSessions)this.userSessions.get(userUuid); + sessions.getSessions().forEach((session) -> { + UUID siteUuid = user.getSiteUuid(); + if (siteUuid == null) { + session.close(CloseStatus.NORMAL); + } else { + boolean apiOnly = user.getSiteInfo(siteUuid).isApiOnly(); + session.close(apiOnly ? CloseStatus.NOT_ACCEPTABLE : CloseStatus.NORMAL); + } + + }); + this.userSessions.remove(userUuid); + } + } + + } + + public void close(UUID uuid, CloseStatus status) { + if (this.deviceSessions != null && this.deviceSessions.containsKey(uuid)) { + ((MidmWebSocketSession)this.deviceSessions.get(uuid)).close(status); + } + + } + + public void notifyOnLineStatus(MidmWebSocketSession midmSession, boolean isOnline) { + this.notifyOnLineStatus(midmSession.isDevice(), midmSession.getSiteUuid(), midmSession.getUuid(), isOnline); + } + + private void notifyOnLineStatus(boolean isDevice, UUID siteUuid, UUID uuid, boolean isOnline) { + if (!isDevice || this.deviceService.updateOnlineStatus(uuid, isOnline).getModifiedCount() != 0L) { + MidmPacket packet = new MidmPacket(); + MidmResponse feedback = new MidmResponse(); + feedback.setCode(211); + Document state = (new Document("isOnline", isOnline)).append(isDevice ? "deviceUuid" : "userUuid", uuid); + feedback.setData(state); + packet.setFeedback(feedback); + this.sendPacketToOnlineUsers(siteUuid, packet); + } + } + + public void updateDeviceStatus(UUID siteUuid, UUID deviceUuid, MidmPacket packet) { + if (this.deviceService.exists(deviceUuid)) { + MidmResponse response = packet.getFeedback(); + Document state = response.getDataAsDbObject(); + this.deviceService.updateDeviceStatus(deviceUuid, state); + state.put("deviceUuid", deviceUuid); + response.setData(state); + this.sendPacketToOnlineUsers(siteUuid, packet); + } + } + + public void sendUpdateFeedback(Device device) { + MidmPacket packet = new MidmPacket(); + packet.setFeedback(114, "", this.optimizeDeviceInfo(device)); + this.sendPacketToOnlineUsers(device.getSiteUuid(), packet); + } + + public void sendMessageToOnlineUsers(Device device, int what) { + MidmPacket packetFeedback = new MidmPacket(); + MidmResponse feedback = new MidmResponse(); + feedback.setCode(what); + JsonObject jState = new JsonObject(); + jState.addProperty("deviceUuid", device.getUuid().toString()); + jState.addProperty("serialNo", device.getSerialNo()); + switch (what) { + case 113: + jState.addProperty("message", "New device has been registered."); + break; + case 114: + jState.addProperty("message", "Device has been updated."); + } + + feedback.setData(jState); + packetFeedback.setFeedback(feedback); + this.sendPacketToOnlineUsers(device.getSiteUuid(), packetFeedback); + } + + public void sendMessageToOnlineUsers(List devices, int what) { + MidmPacket packetFeedback = new MidmPacket(); + MidmResponse feedback = new MidmResponse(); + feedback.setCode(what); + JsonObject jState = new JsonObject(); + jState.addProperty("count", devices.size()); + switch (what) { + case 113: + jState.addProperty("message", "New device has been registered."); + break; + case 114: + jState.addProperty("message", "Device has been updated."); + } + + feedback.setData(jState); + packetFeedback.setFeedback(feedback); + this.sendPacketToOnlineUsers(((Device)devices.get(0)).getSiteUuid(), packetFeedback); + } + + public void sendPacketToOnlineUsers(final UUID siteUuid, MidmPacket packet) { + if (siteUuid != null) { + this.userSessions.forEach((uuid, sessions) -> sessions.sendMessage(siteUuid, packet)); + } + } + + public void sendMessageToOnlineUsers(User user, int what) { + this.sendMessageToOnlineUsers(user.getUuid(), what); + } + + public void sendMessageToOnlineUsers(UUID userUuid, int what) { + MidmPacket packetFeedback = new MidmPacket(); + MidmResponse feedback = new MidmResponse(); + feedback.setCode(what); + JsonObject jState = new JsonObject(); + switch (what) { + case 106: + jState.addProperty("message", "Site upgrade successfully"); + break; + case 107: + jState.addProperty("message", "Site upgrade is requested"); + break; + case 108: + jState.addProperty("message", "Site license is requested"); + break; + case 109: + jState.addProperty("message", "Site license ready"); + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + default: + break; + case 116: + jState.addProperty("message", "New message notified"); + break; + case 117: + jState.addProperty("message", "Report has been uploaded"); + break; + case 118: + jState.addProperty("message", "Report upload fail"); + break; + case 119: + jState.addProperty("message", "Host license ready"); + } + + feedback.setData(jState); + packetFeedback.setFeedback(feedback); + this.sendMessageToOnlineUsers(userUuid, packetFeedback); + } + + public void sendMessageToOnlineUsers(User user, MidmPacket packetFeedback) { + this.sendMessageToOnlineUsers(user.getUuid(), packetFeedback); + } + + public void sendMessageToOnlineUsers(UUID userUuid, MidmPacket packetFeedback) { + if (this.userSessions.containsKey(userUuid)) { + ((UserSocketSessions)this.userSessions.get(userUuid)).sendMessage((UUID)null, packetFeedback); + } + + } + + public void sendFeedback(MidmWebSocketSession midmSession, UUID senderUuid, UUID receiverUuid, MidmPacket packet) { + int feedbackCode = packet.getFeedback().getCode(); + Object feedbackData = packet.getFeedback().getData(); + switch (feedbackCode) { + case 120: + String category = (String)((Map)packet.getQuery().getParam("params")).get("category"); + if ("installed".equals(category)) { + JsonElement jApps = McJsonUtils.toJsonElement(feedbackData); + List deviceApps = (List)McJsonUtils.toObject(jApps, (new TypeToken() { + }).getType()); + this.deviceAppsService.save(senderUuid, deviceApps); + } + break; + case 131: + this.deviceService.update(senderUuid, "profile.hardware_info.storages", feedbackData); + break; + case 190: + this.deviceService.update(senderUuid, "profile.hardware_info.memory", feedbackData); + break; + case 191: + this.deviceService.update(senderUuid, "profile.hardware_info.battery", feedbackData); + DbObject batteryObj = new DbObject((Map)feedbackData); + this.batteryService.updateBatteryFromInstant(midmSession.getDevice(), batteryObj); + break; + case 192: + this.deviceService.update(senderUuid, "profile.network.dataUsage", feedbackData); + break; + case 193: + Map activeNetwork = (Map)feedbackData; + String publicIp = midmSession.getRemoteIpAddress(); + if (!Strings.isNullOrEmpty(publicIp)) { + activeNetwork.put("public_ip", publicIp); + this.deviceService.updateActiveNetwork(senderUuid, publicIp, activeNetwork); + } + break; + case 194: + String networkType = packet.getParam("command").toString(); + if (!Strings.isNullOrEmpty(networkType)) { + this.deviceService.update(senderUuid, "profile.network." + networkType, feedbackData); + } + break; + case 198: + if (((Map)feedbackData).get("available").equals(true)) { + this.deviceReportService.save(midmSession.getDevice(), "location", feedbackData); + } + } + + if (this.deviceSessions.containsKey(receiverUuid)) { + MidmWebSocketSession receiverSession = (MidmWebSocketSession)this.deviceSessions.get(receiverUuid); + if (receiverSession.isOpen()) { + receiverSession.sendMessage(packet); + } + } else if (this.userSessions.containsKey(receiverUuid)) { + UserSocketSessions sessions = (UserSocketSessions)this.userSessions.get(receiverUuid); + sessions.sendMessage((UUID)null, packet); + } + + } + + public void sendMessage(MidmPacket query) { + UUID receiverUuid = query.getRecieverUuid(); + if (receiverUuid != null) { + MidmWebSocketSession session = (MidmWebSocketSession)this.deviceSessions.get(receiverUuid); + if (session != null) { + if (session.isOpen()) { + session.sendPacket(query); + } else { + this.deviceSessions.remove(receiverUuid); + this.sessions.remove(session.sessionId()); + } + } else { + UUID siteUuid = this.deviceService.getSiteUuid(receiverUuid); + if (siteUuid != null) { + this.notifyOnLineStatus(true, siteUuid, receiverUuid, false); + } + } + + } + } + + public void sendPacketToOnlineDevices(MidmPacket packet) { + for(Map.Entry sessionEntry : this.sessions.entrySet()) { + MidmWebSocketSession session = (MidmWebSocketSession)sessionEntry.getValue(); + if (session.isDevice() && session.isOpen()) { + packet.setRecieverUuid(session.getUuid()); + session.sendPacket(packet); + } + } + + } + + public boolean sendMessage(WebSocketSession session, WebSocketMessage message) { + try { + synchronized(session) { + if (session.isOpen()) { + session.sendMessage(message); + return true; + } else { + return false; + } + } + } catch (Exception var6) { + return false; + } + } + + public MidmWebSocketSession toMidmSocketSession(WebSocketSession session, boolean registering) { + if (!session.isOpen()) { + return null; + } else { + MidmWebSocketSession midmSession = this.sessions.containsKey(session.getId()) ? (MidmWebSocketSession)this.sessions.get(session.getId()) : new MidmWebSocketSession(session, this.getHeartBeatInterval()); + if (midmSession == null) { + return null; + } else { + if (midmSession.isFrom("device")) { + String serialNo = midmSession.serialNo(); + Pair pair = this.deviceKeyService.isValidRsa(serialNo, midmSession.encryptString()); + if (Boolean.FALSE == pair.getFirst()) { + String errorMessage = (String)pair.getSecond(); + midmSession.sendFeedback(112, errorMessage, (Object)null); + midmSession.close(CloseStatus.POLICY_VIOLATION); + return null; + } + + Device device = midmSession.getDevice(); + if (device == null) { + device = this.deviceService.findBySerialNo(serialNo); + if (device != null) { + midmSession.setHolder(device); + } + } + + if (device == null && !midmSession.selfEnroll() || device != null && device.isBlocked()) { + String message = "none"; + if (device != null) { + if (!device.getEnabled()) { + message = "disabled"; + } else if (device.isBlocked()) { + message = "blocked"; + } + } + + midmSession.sendFeedback(112, message, (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return null; + } + + if (registering) { + boolean reconnecting = false; + if (device != null && device.getEnabled()) { + reconnecting = this.deviceSessions.containsKey(device.getUuid()); + int curClientVersion = midmSession.clientVersion(); + if (midmSession.selfEnroll()) { + if (!device.getSiteUuid().equals(midmSession.getSiteUuid())) { + String title = this.siteService.getTitle(device.getSiteUuid()); + midmSession.sendFeedback(112, "registered:" + title, (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return null; + } + + this.deviceAppsService.delete(device.getUuid()); + if (midmSession.ifExistsOption() == IF_EXISTS_OPTION.replace) { + Device prevDevice = device; + device = new Device(); + device.init(); + device.setUuid(prevDevice.getUuid()); + if (curClientVersion > 0) { + device.setClientVersion(curClientVersion); + } + + device.setSerialNo(serialNo); + device.setSiteUuid(midmSession.getSiteUuid()); + UUID groupUuid = midmSession.groupUuid(); + this.setDeviceGroup(device, groupUuid); + String owner = midmSession.owner(); + this.setDeviceOwner(device, owner); + device.setEnabled(true); + device.setLicense(prevDevice.getLicense()); + device.setLicensed(prevDevice.getLicensed()); + } else if (midmSession.ifExistsOption() == IF_EXISTS_OPTION.update) { + UUID groupUuid = midmSession.groupUuid(); + this.setDeviceGroup(device, groupUuid); + String owner = midmSession.owner(); + this.setDeviceOwner(device, owner); + } + + if (midmSession.ifExistsOption().option != 0 && !this.hostLicenseService.isStandalone()) { + String licenseIdName = midmSession.licenseId(); + if (!Strings.isNullOrEmpty(licenseIdName) && (device.isTrial() || device.isLicenseExpired())) { + boolean autoRenew = midmSession.autoRenew(); + boolean renewToSameModel = midmSession.renewToSameModel(); + DeviceLicense newLicense = this.deviceService.setLicense(device, licenseIdName, autoRenew, renewToSameModel); + if (newLicense == null || newLicense.isExpired()) { + midmSession.sendFeedback(115); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return null; + } + } + } + + this.deviceService.save(device); + } + + if (device.isEnrolled()) { + if (!this.deviceService.isLicenseAvailable(device)) { + midmSession.sendFeedback(115); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return null; + } + + this.onDeviceCheckedIn(midmSession); + this.updateInstalledApps(device.getUuid(), 5000); + int prevClientVersion = device.getClientVersion(); + if (curClientVersion < 0) { + this.deviceService.scheduleToUpdateProfile(device, 1); + } else { + if (prevClientVersion > curClientVersion) { + this.logService.save((User)null, device.getUuid(), "event", String.format("Close the sesssion to reconnect. The device is supposed to be reset because MiDM apps downgraded(%d -> %d).", prevClientVersion, curClientVersion)); + this.queryDeviceInfo(device.getUuid(), midmSession); + this.deviceService.resetDevice(device, false); + midmSession.close(CloseStatus.NORMAL); + return null; + } + + if (curClientVersion > 0 && prevClientVersion != curClientVersion) { + this.queryDeviceInfo(device.getUuid(), midmSession); + device.setClientVersion(curClientVersion); + this.deviceService.setClientVersion(device.getUuid(), curClientVersion); + } + } + + if (!reconnecting) { + this.updateDeviceInfo(device, midmSession); + } + } else { + midmSession.sendEnrollRequest(device); + } + } else { + if (!midmSession.selfEnroll()) { + midmSession.sendFeedback(112, device == null ? "none" : "disabled", (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return null; + } + + midmSession.sendRequest(MIDM_REQUEST.ENROLL); + } + } + + if (device != null) { + if (this.hostLicenseService.isStandalone()) { + if (!this.hostLicenseService.isValid()) { + midmSession.sendFeedback(115); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return null; + } + } else { + DeviceLicense license; + if (device.hasLicense()) { + license = device.getLicense(); + if (license.isExpired()) { + if (!license.isAutoRenew() || !this.deviceService.renewLicense(device)) { + midmSession.sendFeedback(115); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + return null; + } + } else if (license.isPerpetual()) { + Date nextExpiry = license.getLicenseModel().getNextExpiry(new Date()); + if (license.getExpiry() == null || nextExpiry.after(license.getExpiry())) { + license.setExpiry(nextExpiry); + device.setLicenseExpiry(nextExpiry); + this.deviceService.setLicenseExpiry(device, nextExpiry); + } + } + } else { + license = this.deviceService.setTrialLicense(device); + device.setLicense(license); + this.deviceService.save(device); + } + + if (license != null) { + license.setSite((Site)null); + license.setSiteLicense((SiteLicense)null); + } + } + } + } else { + User user = UserPrincipal.getUser(session); + if (user != null) { + midmSession.setHolder(user); + } + } + + return midmSession; + } + } + } + + private void onDeviceCheckedIn(MidmWebSocketSession midmSession) { + this.deviceService.updateLastCheckedIn(midmSession.getUuid()); + midmSession.sendFeedback(110, "", this.optimizeDeviceInfo(midmSession.getDevice())); + } + + private void setDeviceGroup(Device device, UUID groupUuid) { + if (groupUuid != null) { + DeviceGroup deviceGroup = this.deviceService.findDeviceGroup(groupUuid); + device.setDeviceGroup(deviceGroup); + } + + } + + private void setDeviceOwner(Device device, String ownerEmail) { + if (!Strings.isNullOrEmpty(ownerEmail)) { + User user = this.userService.findUserByEmail(device.getSiteUuid(), ownerEmail); + if (user != null && user.isBelongedToSite(device.getSiteUuid())) { + device.setOwner(user); + } else { + device.setOwner((User)null); + device.setProfile("owner", "email", ownerEmail); + } + } + + } + + public Device optimizeDeviceInfo(Device orgDevice) { + Device device = orgDevice.clone(); + device.getProfile().clear(); + Site site = this.siteService.findByUuid(device.getSiteUuid()); + device.setProfile("site", site.getProfile()); + device.setProfile("site", "siteIdName", site.getIdName()); + device.setOwner((User)null); + DeviceGroup deviceGroup = device.getDeviceGroup(); + if (deviceGroup != null) { + device.setProfile("deviceGroup", deviceGroup.getProfile()); + } + + device.setDeviceGroup((DeviceGroup)null); + device.setSetting("websocket.heartbeat.interval", this.getHeartBeatInterval()); + device.setSetting("installApps", site.getIncludeApps()); + device.setStates((DbObject)null); + device.setLicense((DeviceLicense)null); + device.setEnabled((Boolean)null); + device.setCreated((Date)null); + device.setLastDisconnected((Date)null); + device.setLicensed((Date)null); + return device; + } + + public Device getOnlineDevice(UUID deviceUuid) { + return this.deviceSessions.containsKey(deviceUuid) ? ((MidmWebSocketSession)this.deviceSessions.get(deviceUuid)).getDevice() : null; + } + + public boolean isOnline(UUID uuid) { + return this.deviceSessions.containsKey(uuid) || this.userSessions.containsKey(uuid); + } + + public void ping(UUID uuid) { + if (this.deviceSessions.containsKey(uuid)) { + ((MidmWebSocketSession)this.deviceSessions.get(uuid)).ping(); + } + + } + + private int getHeartBeatInterval() { + return this.settingsService != null ? this.settingsService.getInt("websocket.heartbeat.interval", 300) : 300; + } + + public void updateInstalledApps(UUID deviceUuid) { + MidmWebSocketSession session = (MidmWebSocketSession)this.deviceSessions.get(deviceUuid); + if (session != null) { + MidmPacket packet = new MidmPacket(); + MidmQuery query = new MidmQuery(MIDM_REQUEST.QUERY.getCode()); + packet.setRecieverUuid(deviceUuid); + query.setSenderUuid(UUID.randomUUID()); + query.setRequest("apps"); + query.setParam("command", "list"); + Document params = new Document("category", "installed"); + Site site = this.siteService.findByUuid(session.getSiteUuid()); + String[] includeApps = site.getIncludeApps(); + if (includeApps != null && includeApps.length > 0) { + params.append("includes", includeApps); + } + + query.setParam("params", params); + packet.setQuery(query); + session.sendPacket(packet); + } + + } + + public void updateInstalledApps(UUID deviceUuid, int delay) { + this.taskScheduler.schedule(() -> this.updateInstalledApps(deviceUuid), new Date((new Date()).getTime() + (long)delay)); + } + + public void block(Device device) { + UUID deviceUuid = device.getUuid(); + ReconnectMonitor reconnectMonitor = (ReconnectMonitor)this.reconnectMonitors.get(deviceUuid); + if (reconnectMonitor == null) { + reconnectMonitor = new ReconnectMonitor(device, this); + this.reconnectMonitors.put(deviceUuid, reconnectMonitor); + } + + reconnectMonitor.block(device); + } + + public void unblock(UUID deviceUuid, User loggedUser) { + if (this.reconnectMonitors.containsKey(deviceUuid)) { + ((ReconnectMonitor)this.reconnectMonitors.get(deviceUuid)).unblock(loggedUser); + } + + } + + public void unblockBySiteUuid(UUID siteUuid) { + for(ReconnectMonitor reconnectMonitor : this.reconnectMonitors.values()) { + Device device = reconnectMonitor.getDevice(); + if (siteUuid.equals(device.getSiteUuid())) { + this.unblock(device.getUuid(), (User)null); + } + } + + } + + public void onUnblocked(ReconnectMonitor monitor, User loggedUser) { + UUID deviceUuid = monitor.getDeviceUuid(); + this.logService.save(loggedUser, deviceUuid, "event", loggedUser == null ? "Unblocked by timeout." : "UnBlocked manually."); + this.deviceService.updateBlockState(deviceUuid, (Date)null, (Date)null); + } + + public void onAbused(ReconnectMonitor monitor) { + UUID deviceUuid = monitor.getDeviceUuid(); + ((MidmWebSocketSession)this.deviceSessions.get(deviceUuid)).sendFeedback(112, "blocked", (Object)null); + this.close(deviceUuid, CloseStatus.NOT_ACCEPTABLE); + this.deviceService.updateBlockState(deviceUuid, monitor.getBlockedAt(), monitor.getUnblockAt()); + this.logService.save((User)null, deviceUuid, "event", "Blocked. It will be unblocked at " + monitor.getUnblockAt()); + } +} diff --git a/src/main/java/com/midm/service/news/MessageLogService.java b/src/main/java/com/midm/service/news/MessageLogService.java new file mode 100644 index 0000000..69efd8c --- /dev/null +++ b/src/main/java/com/midm/service/news/MessageLogService.java @@ -0,0 +1,79 @@ +package com.midm.service.news; + +import com.midm.model.news.MessageLog; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.User; +import com.midm.service.BaseService; +import com.mongodb.client.result.DeleteResult; +import java.util.List; +import java.util.UUID; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class MessageLogService extends BaseService { + public MessageLog findLog(UUID messageUuid, UUID userUuid, UUID siteUuid) { + Criteria criteria = Criteria.where("message.$id").is(messageUuid).and("reader.$id").is(userUuid).and("siteUuid").is(siteUuid); + Query query = new Query(criteria); + MessageLog log = (MessageLog)this.mongoTemplate.findOne(query, MessageLog.class); + return log; + } + + public List findLog(UUID userUuid, UUID siteUuid, int limit) { + Criteria criteria = Criteria.where("reader.$id").is(userUuid).orOperator(new Criteria[]{Criteria.where("siteUuid").is(siteUuid), Criteria.where("siteUuid").exists(false)}); + Query query = new Query(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"notified"})); + query.fields().exclude("reader"); + if (limit != 0) { + query.limit(limit); + } + + List log = this.mongoTemplate.find(query, MessageLog.class); + return log; + } + + public List findUnchecked(User user) { + Criteria criteria = Criteria.where("reader.$id").is(user.getUuid()).and("isCheck").is(false).orOperator(new Criteria[]{Criteria.where("siteUuid").is(user.getSiteUuid()), Criteria.where("siteUuid").exists(false)}); + Query query = new Query(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"notified"})); + query.fields().exclude("reader").exclude("siteUuid"); + return this.mongoTemplate.find(query, MessageLog.class); + } + + public List findLogByReadStatus(UUID userUuid, UUID siteUuid, boolean isRead) { + Criteria criteria = Criteria.where("reader.$id").is(userUuid).and("siteUuid").is(siteUuid).and("isRead").exists(isRead); + Query query = new Query(criteria); + List log = this.mongoTemplate.find(query, MessageLog.class); + return log; + } + + public List findLogByCheckStatus(UUID userUuid, UUID siteUuid, boolean isCheck) { + Criteria criteria = Criteria.where("reader.$id").is(userUuid).and("siteUuid").is(siteUuid).and("isCheck").is(isCheck); + Query query = new Query(criteria); + List log = this.mongoTemplate.find(query, MessageLog.class); + return log; + } + + public List findLogsByMessage(UUID messageUuid) { + Criteria criteria = Criteria.where("message.$id").is(messageUuid); + Query query = new Query(criteria); + List logs = this.mongoTemplate.find(query, MessageLog.class); + return logs; + } + + public List findLogByReader(UUID userUuid, UUID messageUuid) { + Criteria criteria = Criteria.where("message.$id").is(messageUuid).and("reader.$id").is(userUuid); + Query query = new Query(criteria); + List log = this.mongoTemplate.find(query, MessageLog.class); + return log; + } + + public DeleteResult deleteByNewsMessage(NewsMessage newsMessage) { + Criteria criteria = Criteria.where("message.$id").is(newsMessage.getUuid()); + Query query = new Query(criteria); + return this.mongoTemplate.remove(query, MessageLog.class); + } +} diff --git a/src/main/java/com/midm/service/news/NewsMessageService.java b/src/main/java/com/midm/service/news/NewsMessageService.java new file mode 100644 index 0000000..d40f344 --- /dev/null +++ b/src/main/java/com/midm/service/news/NewsMessageService.java @@ -0,0 +1,798 @@ +package com.midm.service.news; + +import com.google.common.base.Strings; +import com.google.common.collect.Lists; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceLicense; +import com.midm.model.file.FILE_TYPE; +import com.midm.model.file.REPORT_ERROR; +import com.midm.model.news.MessageLog; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.Site; +import com.midm.model.org.SiteFile; +import com.midm.model.org.SiteInfo; +import com.midm.model.org.User; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.device.DeviceService; +import com.midm.service.file.FileService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.SiteService; +import com.midm.service.store.StoreAppService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.SettingsService; +import com.midm.service.template.TemplateService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.internet.mail.McMailSender; +import com.mitac.cell.utils.McEmailUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.AggregateIterable; +import com.mongodb.client.result.UpdateResult; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.mail.internet.InternetAddress; +import org.bson.Document; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; + +@Service +public class NewsMessageService extends BaseService { + @Autowired + @Lazy + @Qualifier("fileService") + private FileService fileService; + @Autowired + private EmailService emailService; + @Autowired + private MessageLogService messageLogService; + @Autowired + private SettingsService settingsService; + @Autowired + @Lazy + private StoreAppService storeAppService; + @Autowired + private WebSocketSessionManager sessionManager; + @Autowired + private TemplateService templateService; + @Autowired + @Qualifier("stringTemplateEngine") + private TemplateEngine stringTemplateEngine; + @Autowired + @Lazy + private HostLicenseService hostLicenseService; + @Autowired + @Lazy + private SiteService siteService; + + public NewsMessage save(NewsMessage newsMessage) { + NewsMessage message = (NewsMessage)this.saveDocument(newsMessage); + Date schedule = message.getSendSchedule(); + if (schedule != null && schedule.after(new Date())) { + this.scheduleToNotify(message); + } + + return message; + } + + public NewsMessage generateNewsMessage(Device device) { + NewsMessage newsMessage = null; + if (device != null) { + newsMessage = new NewsMessage(device); + } else { + newsMessage = new NewsMessage(); + } + + return newsMessage; + } + + public NewsMessage setNewsMessage(String title, String content, String summary, String category, Set roles, Device device) { + NewsMessage newsMessage = device != null ? new NewsMessage(device, category) : new NewsMessage(); + newsMessage.setMessage(title, content, summary); + return newsMessage; + } + + public void delete(MessageLog messageLog) { + this.deleteById(MessageLog.class, messageLog.getUuid()); + } + + public void delete(NewsMessage newsMessage) { + this.deleteById(NewsMessage.class, newsMessage.getUuid()); + this.messageLogService.deleteByNewsMessage(newsMessage); + } + + public void delete(List newsMessage) { + List uuids = (List)newsMessage.stream().map(NewsMessage::getUuid).collect(Collectors.toList()); + Query query = Query.query(Criteria.where("_id").in(uuids)); + this.mongoTemplate.remove(query, NewsMessage.class); + } + + public NewsMessage findMessage(UUID uuid) { + return (NewsMessage)this.findById(NewsMessage.class, uuid); + } + + public List findAll() { + return this.findAll(NewsMessage.class); + } + + public List findByUser(User user, boolean isUnreadOnly, int size) { + List newsMessage = null; + return newsMessage; + } + + public Page find(String category, String forWhat, JsonObject jFilter, String sortBy, Sort.Direction direction, Integer page, Integer size) { + Criteria criteria = new Criteria(); + if (!Strings.isNullOrEmpty(category)) { + criteria.and("category").is(category); + } + + if (!Strings.isNullOrEmpty(forWhat)) { + criteria.and("forWhat").is(forWhat); + } + + Query query = Query.query(criteria); + if (jFilter != null) { + McMongoUtils.addFilter(query, jFilter); + } + + if (McStringUtils.isValid(sortBy)) { + if (direction == null) { + direction = Direction.ASC; + } + + query.with(Sort.by(direction, new String[]{sortBy})); + } + + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, NewsMessage.class); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), NewsMessage.class); + Page pageResult = new PageImpl(result, pageable, total); + return pageResult; + } + + public Collection saveMessageLog(NewsMessage newsMessage) { + this.setGlobalMessageLog(newsMessage); + Collection sendMails = this.getEmailLists(newsMessage.getCategory(), newsMessage.getForWhat(), true); + Collection notiMails = this.getEmailLists(newsMessage.getCategory(), newsMessage.getForWhat(), false); + notiMails.forEach((user) -> { + if (this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((UUID)user.getUuid(), 116); + } + + }); + return sendMails; + } + + public void notifyMessage(NewsMessage newsMessage) { + Collection mails = this.saveMessageLog(newsMessage); + this.sendNotification(mails, newsMessage); + } + + private void sendNotification(Collection mails, NewsMessage message) { + Map recipients = (Map)mails.stream().collect(Collectors.toMap(UserMail::getEmail, (user) -> user.toAddress())); + List mailsTo = message.getMailsTo(); + if (mailsTo != null && !mailsTo.isEmpty()) { + mailsTo.forEach((address) -> recipients.put(address.getAddress(), address)); + } + + this.getAllExtraReceivers(message.getCategory(), message.getForWhat()).forEach((address) -> recipients.put(address.getAddress(), address)); + String extraReceipientValue = this.settingsService.get("recipients.siteRequest"); + if (!Strings.isNullOrEmpty(extraReceipientValue)) { + List extraReceipients = McEmailUtils.parseMails(extraReceipientValue); + if (extraReceipients != null && !extraReceipients.isEmpty()) { + extraReceipients.forEach((address) -> recipients.put(address.getAddress(), address)); + } + } + + if (!recipients.isEmpty()) { + String template = this.getHtml(message, message.getUuid()); + McMailSender sender = this.emailService.getMailSender(message.getTitle(), template, true); + if (sender != null) { + this.sendMail(sender, (List)recipients.values().stream().collect(Collectors.toList())); + } + } + } + + private void sendMail(McMailSender sender, List addresses) { + for(List oneList : Lists.partition(addresses, 40)) { + sender.clearBcc(); + sender.addBcc(oneList); + sender.send(); + } + + } + + public List getMessageByCategory(String category) { + Query query = Query.query(Criteria.where("category").is(category)); + return this.mongoTemplate.find(query, NewsMessage.class); + } + + public void setMessageLog(NewsMessage message, User reader, Site site) { + MessageLog log = new MessageLog(message, reader, site.getUuid()); + this.saveMessageLog(log); + } + + public void setMessageLog(NewsMessage message, UUID userUuid, UUID siteUuid) { + if (message != null && userUuid != null) { + MessageLog log = new MessageLog(message, userUuid, siteUuid); + this.saveMessageLog(log); + } + + } + + public void saveMessageLog(MessageLog log) { + this.saveDocument(log); + } + + public void deleteMessageLog(NewsMessage... messages) { + } + + public MessageLog findLog(UUID newsUuid, UUID userUuid, UUID siteUuid) { + MessageLog log = this.messageLogService.findLog(newsUuid, userUuid, siteUuid); + return log; + } + + public List findLogsByUserAndSite(User user, int limit) { + List log = this.messageLogService.findLog(user.getUuid(), user.getSiteUuid(), limit); + return log; + } + + public Document recentMessages(User user, int limit) { + List pipeline = Arrays.asList(new Document("$match", new Document("$and", new Document[]{new Document("$or", Arrays.asList(new Document("siteUuid", user.getSiteUuid()), new Document("siteUuid", new Document("$exists", false)))), new Document("reader.$id", user.getUuid())})), new Document("$group", (new Document("_id", (Object)null)).append("unread", new Document("$sum", new Document("$cond", Arrays.asList("$isRead", 0, 1)))).append("uncheck", new Document("$sum", new Document("$cond", Arrays.asList("$isCheck", 0, 1))))), new DbObject("$project", new Document("_id", 0))); + Document result = (Document)this.mongoTemplate.aggregate(Aggregations.from(pipeline), MessageLog.class, Document.class).getUniqueMappedResult(); + Document messages = result == null ? (new Document("unread", 0)).append("uncheck", 0) : result; + List logs = this.findLogsByUserAndSite(user, limit); + messages.put("messages", logs); + return messages; + } + + public List findUnchecked(User user) { + return null; + } + + public List findUnreadLogsByUserAndSite(User user) { + List log = this.messageLogService.findLogByReadStatus(user.getUuid(), user.getSiteUuid(), false); + return log; + } + + public UpdateResult setMessageAsCheck(User user) { + return this.mongoTemplate.updateMulti(Query.query(Criteria.where("reader.$id").is(user.getUuid()).and("isCheck").is(false)), Update.update("isCheck", true).set("checkDate", new Date()), MessageLog.class); + } + + public UpdateResult setMessageAsCheck(UUID uuid) { + return this.mongoTemplate.updateMulti(Query.query(Criteria.where("_id").is(uuid)), Update.update("isCheck", true).set("checkDate", new Date()), MessageLog.class); + } + + public UpdateResult markAllMessageAsRead(User user, UUID siteUuid) { + return this.mongoTemplate.updateMulti(Query.query(Criteria.where("reader.$id").is(user.getUuid()).and("siteUuid").is(siteUuid).and("readDate").exists(false)), Update.update("readDate", new Date()), MessageLog.class); + } + + public long countUnread(User user) { + Criteria criteria = (new Criteria()).andOperator(new Criteria[]{Criteria.where("reader.$id").is(user.getUuid()), Criteria.where("siteUuid").is(user.getSiteUuid()), Criteria.where("readDate").exists(false)}); + return this.mongoTemplate.count(Query.query(criteria), MessageLog.class); + } + + public String getHtml(NewsMessage message, UUID newsUuid) { + String template = null; + if (message == null) { + message = (NewsMessage)this.findById(NewsMessage.class, newsUuid); + } + + if (message != null) { + Context context = new Context(); + context.setVariable("message", message); + TemplateService var10000 = this.templateService; + String var10001 = message.getCategory(); + template = var10000.getTemplate("noti." + var10001 + "." + message.getForWhat()); + template = this.stringTemplateEngine.process(template, context); + } + + return template; + } + + @Scheduled( + cron = "0 20 0 * * *" + ) + @Async + protected void maintainMessages() { + if (this.hostLicenseService.isPrimaryServer()) { + this.sendScheduledMessage(); + this.removeExpiredMessages(); + if (DateTime.now().getDayOfWeek() == 7) { + this.licenseExpirySendMessage(); + } + + } + } + + public void sendScheduledMessage() { + Date today = DateTime.now().toLocalDate().toDate(); + Query query = Query.query(Criteria.where("sendSchedule").is(today)); + + for(NewsMessage newsMessage : this.mongoTemplate.find(query, NewsMessage.class)) { + if (newsMessage.isEnabled()) { + this.notifyMessage(newsMessage); + } + } + + } + + @Async + public void removeExpiredMessages() { + Date today = LocalDate.now().toDate(); + Query query = Query.query(Criteria.where("expiry").lt(today)); + + for(NewsMessage newsMessage : this.mongoTemplate.find(query, NewsMessage.class)) { + this.delete(newsMessage); + } + + } + + private void verifyExpiringDeviceLicenses() { + this.expireTrialLicense(); + this.verifyExpiringDate(); + } + + private void expireTrialLicense() { + List pipeline = Arrays.asList(new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$licenseModel"), 1)))), new Document("$lookup", (new Document("from", "licenseModel")).append("foreignField", "_id").append("localField", "licenseModel.v").append("as", "licenseModel")), new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList("$licenseModel", 0)))), new Document("$match", new Document("licenseModel.name", "Trial")), new Document("$match", new Document("expiry", new Document("$gte", new Date()))), new Document("$lookup", (new Document("from", "device")).append("foreignField", "profile.hardware_info.serial_no").append("localField", "deviceSerial").append("as", "device")), new Document("$addFields", new Document("device", new Document("$arrayElemAt", Arrays.asList("$device", 0)))), new Document("$addFields", new Document("device.license", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$device.license"), 1)))), new Document("$match", new Document("$expr", new Document("$ne", Arrays.asList(new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$device.licenseExpiry")), new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$expiry"))))))); + AggregateIterable results = this.getCollection(DeviceLicense.class).aggregate(pipeline); + results.allowDiskUse(true); + Date expireDate = (new LocalDate()).minusDays(1).toDate(); + results.forEach((result) -> this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(result.get("_id"))), Update.update("expiry", expireDate), DeviceLicense.class)); + } + + private void verifyExpiringDate() { + List pipeline = new ArrayList(Arrays.asList(new Document("$match", new Document("licenseExpiry", new Document("$exists", true))), new Document("$addFields", new Document("license", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$license"), 1)))), new Document("$lookup", (new Document("from", "deviceLicense")).append("foreignField", "_id").append("localField", "license.v").append("as", "deviceLicense")), new Document("$addFields", new Document("deviceLicense", new Document("$arrayElemAt", Arrays.asList("$deviceLicense", 0)))), new Document("$match", new Document("deviceLicense.expiry", new Document("$gte", new Date()))), new Document("$match", new Document("$expr", new Document("$ne", Arrays.asList(new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$deviceLicense.expiry")), new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$licenseExpiry")))))))); + AggregateIterable results = this.getCollection(Device.class).aggregate(pipeline); + results.allowDiskUse(true); + results.forEach((result) -> { + Date deviceLicenseExpiry = (Date)((Map)result.get("deviceLicense")).get("expiry"); + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(result.get("_id"))), Update.update("licenseExpiry", deviceLicenseExpiry), Device.class); + }); + } + + public void licenseExpirySendMessage() { + this.verifyExpiringDeviceLicenses(); + Date today = (new LocalDate()).toDate(); + Date dayAfter10 = (new LocalDate()).plusDays(10).toDate(); + Date dayAfter30 = (new LocalDate()).plusDays(30).toDate(); + Date dayAfter45 = (new LocalDate()).plusDays(45).toDate(); + List pipeline = Arrays.asList(new Document("$match", new Document("expiry", (new Document("$gte", today)).append("$lt", dayAfter45))), new Document("$addFields", new Document("site", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$site"), 1)))), new Document("$lookup", (new Document("from", "site")).append("foreignField", "_id").append("localField", "site.v").append("as", "site")), new Document("$addFields", new Document("site", new Document("$arrayElemAt", Arrays.asList("$site", 0)))), new Document("$addFields", new Document("childSite", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$childSite"), 1)))), new Document("$lookup", (new Document("from", "site")).append("foreignField", "_id").append("localField", "childSite.v").append("as", "childSite")), new Document("$addFields", new Document("childSite", new Document("$arrayElemAt", Arrays.asList("$childSite", 0)))), new Document("$project", (new Document("expiry", 1)).append("site", new Document("$ifNull", Arrays.asList("$childSite", "$site")))), new Document("$match", new Document("$expr", new Document("$or", Arrays.asList(new Document("$eq", Arrays.asList("$site.settings.noti.license.expiredIn10.enabled", true)), new Document("$eq", Arrays.asList("$site.settings.noti.license.expiredIn30.enabled", true)), new Document("$eq", Arrays.asList("$site.settings.noti.license.expiredIn45.enabled", true)))))), new Document("$lookup", (new Document("from", "user")).append("localField", "site._id").append("foreignField", "sites.siteUuid").append("as", "users")), new Document("$group", (new Document("_id", "$site._id")).append("site", new Document("$first", "$site")).append("users", new Document("$first", "$users")).append("expireIn10", new Document("$sum", new Document("$cond", Arrays.asList(new Document("$and", Arrays.asList(new Document("$gte", Arrays.asList("$expiry", today)), new Document("$lt", Arrays.asList("$expiry", dayAfter10)))), 1, 0)))).append("expireIn30", new Document("$sum", new Document("$cond", Arrays.asList(new Document("$and", Arrays.asList(new Document("$gte", Arrays.asList("$expiry", dayAfter10)), new Document("$lt", Arrays.asList("$expiry", dayAfter30)))), 1, 0)))).append("expireIn45", new Document("$sum", new Document("$cond", Arrays.asList(new Document("$and", Arrays.asList(new Document("$gte", Arrays.asList("$expiry", dayAfter30)), new Document("$lt", Arrays.asList("$expiry", dayAfter45)))), 1, 0)))).append("total", new Document("$sum", 1))), new Document("$project", (new Document("site", (new Document("idName", "$site.idName")).append("name", "$site.profile.name"))).append("siteUuid", "$site._id").append("users", 1).append("sendMail", "$site.settings.noti.sendEmail").append("roles", (new Document()).append("in10", new Document("$cond", Arrays.asList("$site.settings.noti.license.expiredIn10.enabled", "$site.settings.noti.license.expiredIn10.roles", "$$REMOVE"))).append("in30", new Document("$cond", Arrays.asList("$site.settings.noti.license.expiredIn30.enabled", "$site.settings.noti.license.expiredIn30.roles", "$$REMOVE"))).append("in45", new Document("$cond", Arrays.asList("$site.settings.noti.license.expiredIn45.enabled", "$site.settings.noti.license.expiredIn45.roles", "$$REMOVE")))).append("expiring", (new Document("in10", "$expireIn10")).append("in30", "$expireIn30").append("in45", "$expireIn45").append("total", "$total")))); + AggregateIterable results = this.getCollection(DeviceLicense.class).aggregate(pipeline); + results.forEach((result) -> this.saveLicenseMessage(result)); + } + + public void saveLicenseMessage(Document result) { + Document roles = (Document)result.get("roles"); + if (roles != null && !roles.isEmpty()) { + List users = this.convertToList(User.class, result.getList("users", Document.class)); + if (users != null) { + UUID siteUuid = (UUID)result.get("siteUuid"); + Document site = (Document)result.get("site"); + NewsMessage message = new NewsMessage(); + message.setExpiry((new LocalDate()).plusDays(7).toDate()); + message.setSendSchedule(message.getCreated()); + message.setCategory("license"); + message.setForWhat("expiring"); + Document expiring = (Document)result.get("expiring"); + expiring.getInteger("total", 0); + int in10 = expiring.getInteger("in10", 0); + int in30 = expiring.getInteger("in30", 0); + int in45 = expiring.getInteger("in45", 0); + message.setReference(new DbObject(expiring)); + Set userRoles = null; + int subTotal = in10; + StringBuilder sbContent = new StringBuilder("There're license to be expired, "); + StringBuilder sbSummary = new StringBuilder(); + if (roles.containsKey("in10")) { + if (in10 <= 0) { + return; + } + + expiring.append("subTotal", in10); + userRoles = ((Document)roles.get("in10")).keySet(); + String text = String.format("%d in 10 days", in10); + sbContent.append(text); + } + + if (roles.containsKey("in30")) { + userRoles = ((Document)roles.get("in30")).keySet(); + subTotal = in10 + in30; + if (subTotal <= 0) { + return; + } + + expiring.append("subTotal", subTotal); + String text = String.format("%d in 30 days", subTotal); + sbContent.append(text); + sbSummary.append(text); + } + + if (roles.containsKey("in45")) { + userRoles = ((Document)roles.get("in45")).keySet(); + subTotal += in30 + in45; + if (subTotal <= 0) { + return; + } + + expiring.append("subTotal", subTotal); + String text = String.format("%d in 45 days", subTotal); + sbContent.append(text); + sbSummary.append(text); + } + + sbContent.append("."); + sbSummary.append("."); + message.setTitle(String.format("%d device license is expiring.", subTotal)); + message.setContent(sbContent.toString()); + message.setSummary(sbSummary.toString()); + this.save(message); + if (this.emailService.hasMailServer()) { + McMailSender sender = this.emailService.getMailSender(); + boolean sendMail = result.getBoolean("sendMail", false); + String template = this.templateService.getTemplate("noti.license"); + if (sendMail) { + Context context = new Context(); + context.setVariable("site", site); + context.setVariable("expiring", expiring); + context.setVariable("roles", roles); + template = this.stringTemplateEngine.process(template, context); + } + + int count = 0; + + for(User user : users) { + SiteInfo siteInfo = user.getSiteInfo(siteUuid); + if (siteInfo != null && siteInfo.hasRole((Collection)userRoles)) { + this.setMessageLog(message, user.getUuid(), siteUuid); + if (this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)user, 116); + } + + if (sendMail) { + if (count == 0) { + sender = this.emailService.getMailSender(message.getTitle(Locale.US.toLanguageTag()), template, true); + } + + sender.addTo(user.getEmail(), user.getName()); + ++count; + if (count == 40) { + sender.send(); + count = 0; + } + } + } + } + + if (sendMail && sender.hasRecipients()) { + sender.send(); + } + + } + } + } + } + + public void saveOrUpdateInstallError(Device device, DbObject dbProperty) { + REPORT_ERROR error = REPORT_ERROR.fromValue(dbProperty.getInteger("reason")); + UUID fileUuid = UUID.fromString(dbProperty.getString("fileUuid")); + String type = dbProperty.getString("category"); + UUID siteUuid = device.getSiteUuid(); + String fileName = this.fileService.getFileName(fileUuid, "ota".equals(type) ? FILE_TYPE.OTA : ("app".equals(type) ? FILE_TYPE.APK : FILE_TYPE.FILE)); + NewsMessage message = this.findInstallErrorMessage(fileUuid, error); + if (message == null) { + message = new NewsMessage(); + message.setCategory(DeviceService.KEY.install_error.name()); + message.setForWhat(type); + message.setExpiry((new LocalDate()).plusDays(7).toDate()); + DbObject ref = new DbObject(); + ref.put("fileUuid", fileUuid); + ref.put("fileName", fileName); + ref.put("siteUuid", siteUuid); + ref.put("errorCode", error.getValue()); + Set ssnSet = null; + if (REPORT_ERROR.COLLECT_SSN.contains(error)) { + Set ssnSet = new HashSet(Arrays.asList(device.getSerialNo())); + ref.put("device", new HashSet(ssnSet)); + } + + message.setReference(ref); + this.save(message); + } else if (REPORT_ERROR.COLLECT_SSN.contains(error)) { + List list = message.getReference().getList("device", String.class); + Set ssnSet = list == null ? new HashSet() : new HashSet(list); + if (!ssnSet.contains(device.getSerialNo())) { + ssnSet.add(device.getSerialNo()); + JsonObject jFilter = new JsonObject(); + jFilter.addProperty("_id", message.getUuid().toString()); + Map valueMap = new HashMap(); + valueMap.put("reference.device", ssnSet); + valueMap.put("expiry", (new LocalDate()).plusDays(7).toDate()); + this.update(NewsMessage.class, jFilter, valueMap); + } + } + + } + + public void sendReportMessage(User user, Site site, String forWhat, SiteFile report, boolean success, boolean mailMe) { + if (success && report != null) { + NewsMessage message = new NewsMessage(); + message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); + message.setCategory("report"); + message.setForWhat(forWhat); + String title = "[Report]"; + if (forWhat.startsWith("device")) { + title = "[Device report]"; + } else if (forWhat.startsWith("profile")) { + title = "[Configuration profile report]"; + } else if (forWhat.startsWith("license")) { + title = "[License report]"; + } else if (forWhat.startsWith("site")) { + title = "[Site report]"; + } + + String format = "The report requested at %s"; + if (success) { + message.getReference().put("fileUuid", report.getFileUuid()); + message.getReference().put("fileName", report.getFileName()); + title = title + " Generated"; + format = format + " generated successfully."; + } + + message.getMessage("en-US").put("title", title); + String content = String.format(format, (new SimpleDateFormat()).format(report.getRequested())); + message.getMessage("en-US").put("content", content); + message.getMessage("en-US").put("summary", content); + this.save(message); + if (user.getEnabled()) { + this.setMessageLog(message, user, site); + if (this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)user, 117); + } + + if (mailMe) { + String filePath = this.fileService.getFilePath(user.getSiteUuid(), "report", report.getFileUuid()); + String fileName = report.getFileName(); + DateFormat dateFormat = new SimpleDateFormat("EE-MM-dd-yyyy"); + message.getReference().put("reportExpiry", dateFormat.format(report.getExpiry())); + message.getReference().put("siteName", report.getSiteName()); + this.emailService.sendNotificationRequest(user, message, filePath, fileName); + } + + } + } else { + if (this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)user, 117); + } + + } + } + + public NewsMessage findInstallErrorMessage(UUID fileUuid, REPORT_ERROR errorCode) { + Criteria criteria = Criteria.where("category").is(DeviceService.KEY.install_error.name()).and("reference.fileUuid").is(fileUuid).and("reference.errorCode").is(errorCode.getValue()); + Query query = Query.query(criteria); + return (NewsMessage)this.mongoTemplate.findOne(query, NewsMessage.class); + } + + private void saveMessageLog(NewsMessage newsMessage, Site site) { + Criteria criteria = new Criteria(); + criteria.andOperator(new Criteria[]{Criteria.where("enabled").is(true), Criteria.where("sites.siteUuid").is(site.getUuid()), Criteria.where("sites.enabled").is(true)}); + Query query = Query.query(criteria); + List users = this.mongoTemplate.find(query, User.class); + users.forEach((user) -> { + DbObject messageRoles = site.getSettingsCategory(new String[]{"noti", newsMessage.getCategory(), newsMessage.getForWhat(), "roles"}); + messageRoles.keySet().forEach((role) -> { + if (user.hasRole(site.getUuid(), role)) { + this.setMessageLog(newsMessage, user.getUuid(), site.getUuid()); + } + + }); + }); + } + + private void setGlobalMessageLog(NewsMessage newsMessage) { + String setting = "settings.noti"; + String category = newsMessage.getCategory(); + String forWhat = newsMessage.getForWhat(); + String notiKey = "settings.noti." + category + "." + forWhat; + Criteria criteria = new Criteria(); + criteria.andOperator(new Criteria[]{Criteria.where("enabled").is(true), Criteria.where(notiKey + ".enabled").is(true), Criteria.where(notiKey + ".roles").exists(true)}); + Query query = Query.query(criteria); + List sites = this.mongoTemplate.find(query, Site.class); + sites.forEach((site) -> this.saveMessageLog(newsMessage, site)); + } + + private Collection getEmailLists(String category, String forWhat, boolean notifyByMail) { + String setting = "settings.noti"; + String notiKey = "settings.noti." + category + "." + forWhat; + Document matchStage = new Document("$match", new Document("$and", Arrays.asList(new Document("enabled", true), notifyByMail ? new Document("settings.noti.sendEmail", true) : new Document(), new Document(notiKey + ".enabled", true), new Document(notiKey + ".roles", (new Document("$exists", true)).append("$ne", new Document()).append("$not", new Document("$size", 0)))))); + AggregationOperation matchOp = Aggregations.newOperation(matchStage); + Document lookupStage = new Document("$lookup", (new Document("from", "user")).append("let", new Document("siteUuid", "$_id")).append("pipeline", Arrays.asList(new Document("$unwind", "$sites"), new Document("$match", new Document("$and", Arrays.asList(new Document("$expr", new Document("$and", Arrays.asList(new Document("$eq", Arrays.asList("$sites.siteUuid", "$$siteUuid")), new Document("$eq", Arrays.asList("$sites.enabled", true))))), new Document("enabled", true)))), new Document("$project", (new Document("email", 1)).append("name", "$profile.name").append("roles", "$sites.roles")))).append("as", "users")); + AggregationOperation lookupOp = Aggregations.newOperation(lookupStage); + Document projectStage = new Document("$project", (new Document("roles", "$" + notiKey + ".roles")).append("users", 1)); + AggregationOperation projectOp = Aggregations.newOperation(projectStage); + AggregationResults results = this.mongoTemplate.aggregate(Aggregation.newAggregation(new AggregationOperation[]{matchOp, lookupOp, projectOp}), Site.class, SiteUsers.class); + Map mailMap = new HashMap(); + results.forEach((users) -> { + if (users.getUsers() != null) { + users.getUsers().forEach((user) -> { + if (user.hasRole(users.getRoles()) && !mailMap.containsKey(user.getEmail())) { + mailMap.put(user.getEmail(), user); + } + + }); + } + + }); + return mailMap.values(); + } + + private Collection getAllExtraReceivers(String category, String forWhat) { + String setting = "settings.noti"; + String notiKey = "settings.noti." + category + "." + forWhat + ".enabled"; + Query query = Query.query(Criteria.where("settings.noti.sendEmail").is(true).and(notiKey).is(true).and("settings.noti.receivers").exists(true)); + List receivers = this.mongoTemplate.findDistinct(query, "settings.noti.receivers", Site.class, String.class); + Map addresses = new HashMap(); + receivers.forEach((to) -> { + List tempAddresses = McEmailUtils.parseMails(to); + if (tempAddresses != null && !tempAddresses.isEmpty()) { + tempAddresses.forEach((address) -> addresses.put(address.getAddress(), address)); + } + + }); + return new ArrayList(addresses.values()); + } + + private void scheduleToNotify(final NewsMessage message) { + if (message.getSendSchedule() != null) { + this.schedule(new Runnable() { + public void run() { + NewsMessageService.this.notifyMessage(message); + } + }, message.getSendSchedule()); + } + + } + + @Async + public void scheduleToNotify() { + Criteria criteria = Criteria.where("enabled").is(true).and("sendSchedule").gt(new Date()); + List messages = this.mongoTemplate.find(Query.query(criteria), NewsMessage.class); + messages.forEach((message) -> this.scheduleToNotify(message)); + } + + private class SiteUsers { + private HashMap roles; + private List users; + + public HashMap getRoles() { + return this.roles; + } + + public void setRoles(HashMap roles) { + this.roles = roles; + } + + public List getUsers() { + return this.users; + } + + public void setUsers(List users) { + this.users = users; + } + + public List getEmails() { + List mails = new ArrayList(); + this.users.forEach((user) -> { + if (user.hasRole(this.roles)) { + mails.add(user); + } + + }); + return mails; + } + } + + private static class UserMail { + private String _id; + private String email; + private String name; + private String[] roles; + + public UUID getUuid() { + return UUID.fromString(this._id); + } + + public String getId() { + return this._id; + } + + public void setId(String _id) { + this._id = _id; + } + + public String getEmail() { + return this.email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String[] getRoles() { + return this.roles; + } + + public void setRoles(String[] roles) { + this.roles = roles; + } + + public boolean hasRole(Map roles) { + if (this.roles != null && roles != null) { + for(String role : this.roles) { + if (roles.containsKey(role) && ((Boolean)roles.get(role)).equals(true)) { + return true; + } + } + } + + return false; + } + + public InternetAddress toAddress() { + try { + return new InternetAddress(this.email, this.name); + } catch (Exception var2) { + return null; + } + } + + public String toString() { + return Strings.isNullOrEmpty(this.getName()) ? this.getEmail() : String.format("%s<%s>", this.getName(), this.getEmail()); + } + } +} diff --git a/src/main/java/com/midm/service/org/SiteLicenseService.java b/src/main/java/com/midm/service/org/SiteLicenseService.java new file mode 100644 index 0000000..4ceb92e --- /dev/null +++ b/src/main/java/com/midm/service/org/SiteLicenseService.java @@ -0,0 +1,614 @@ +package com.midm.service.org; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.device.DeviceLicense; +import com.midm.model.log.MidmLog; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.Site; +import com.midm.model.org.SiteLicense; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.log.LogService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.news.NewsMessageService; +import com.midm.service.system.LicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.DBRef; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.mail.internet.InternetAddress; +import org.bson.Document; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.aggregation.ConditionalOperators; +import org.springframework.data.mongodb.core.aggregation.GroupOperation; +import org.springframework.data.mongodb.core.aggregation.LookupOperation; +import org.springframework.data.mongodb.core.aggregation.MatchOperation; +import org.springframework.data.mongodb.core.aggregation.ObjectOperators; +import org.springframework.data.mongodb.core.aggregation.ProjectionOperation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.data.support.PageableExecutionUtils; +import org.springframework.stereotype.Service; + +@Service +public class SiteLicenseService extends BaseService { + @Autowired + @Lazy + private SiteService siteService; + @Autowired + @Lazy + private NewsMessageService newsMessageService; + @Autowired + private SettingsService settingsService; + @Autowired + private EmailService emailService; + @Autowired + private UserService userService; + @Autowired + private WebSocketSessionManager sessionManager; + @Autowired + private LicenseService licenseService; + @Autowired + private LogService logService; + + public SiteLicense save(SiteLicense license) { + if (license.getSite().isChild()) { + license.setChildSite(license.getSite().getReseller()); + } + + if (!license.getStatus().equals(SiteLicense.STATUS.PROCESSING) && !license.getStatus().equals(SiteLicense.STATUS.ORDERED)) { + if (license.getStatus().equals(SiteLicense.STATUS.REJECTED) || license.getStatus().equals(SiteLicense.STATUS.CANCELED)) { + if (license.isForChildSite()) { + this.addLog(license, false, "cancelFrom", "License canceled"); + this.addLog(license, true, "cancel", "License canceled"); + } else { + this.addLog(license, false, "cancel", "License canceled"); + } + } + } else if (license.isForChildSite()) { + this.addLog(license, false, "requestFrom", "License requested"); + this.addLog(license, true, "request", "License requested"); + } else { + this.addLog(license, false, "request", "License requested"); + } + + return (SiteLicense)this.saveDocument(license); + } + + public void addLog(SiteLicense license, boolean forChild, String activity, String message) { + MidmLog addLog = new MidmLog(); + if (forChild) { + addLog.setForWhat(license.getChildSite().getUuid()); + } else { + addLog.setForWhat(license.getSite().getUuid()); + } + + addLog.setCategory("license"); + addLog.setLog(message); + if ((activity.equals("assign") || activity.equals("requestFrom") || activity.equals("cancelFrom")) && license.getChildSite() != null) { + addLog.addReference("to", String.format("%s(%s)", license.getChildSite().getName(), license.getChildSite().getIdName())); + } + + addLog.addReference("activity", activity); + Document licenseObject = new Document(); + licenseObject.put("uuid", license.getUuid()); + licenseObject.put("plan", license.getPlan()); + licenseObject.put("model", license.getLicenseModel().getName()); + licenseObject.put("amount", license.getAmount()); + addLog.addReference("license", licenseObject); + this.logService.save(addLog); + } + + public SiteLicense getSiteLicense(UUID siteLicenseUuid) { + SiteLicense license = (SiteLicense)this.mongoTemplate.findById(siteLicenseUuid, SiteLicense.class); + return license; + } + + public void updateSiteLicense(Site site, String targetPlan) { + String siteType = site.isChild() ? "childSite" : "site"; + Query query = Query.query(Criteria.where(siteType).is(site).and("status").in(new Object[]{"PROCESSING", "ORDERED"})); + Update update = new Update(); + update.set("plan", targetPlan); + this.mongoTemplate.updateMulti(query, update, SiteLicense.class); + } + + public void deleteBySite(UUID siteUuid) { + Criteria siteCriteria = Criteria.where("site.$id").is(siteUuid); + this.mongoTemplate.remove(Query.query(siteCriteria), DeviceLicense.class); + Criteria childSiteCriteria = Criteria.where("childSite.$id").is(siteUuid); + List siteLicenses = this.mongoTemplate.find(Query.query(childSiteCriteria), SiteLicense.class); + if (!siteLicenses.isEmpty()) { + List siteLicenseUuids = (List)siteLicenses.stream().map(SiteLicense::getUuid).collect(Collectors.toList()); + Update update = Update.update("expiry", new Date()); + this.mongoTemplate.updateMulti(Query.query(Criteria.where("siteLicense.$id").in(siteLicenseUuids)), update, DeviceLicense.class); + } + + Criteria criteria = (new Criteria()).orOperator(new Criteria[]{siteCriteria, childSiteCriteria}); + this.mongoTemplate.remove(Query.query(criteria), SiteLicense.class); + } + + public boolean hasSiteLicense(Site site) { + String key = site.isChild() ? "childSite" : "site"; + key = key + ".$id"; + Query query = Query.query(Criteria.where(key).is(site.getUuid())); + return this.mongoTemplate.count(query, SiteLicense.class) > 0L; + } + + public List getPlans(Site site) { + String key = site.isChild() ? "childSite" : "site"; + key = key + ".$id"; + Query query = Query.query(Criteria.where(key).is(site.getUuid())); + return this.mongoTemplate.findDistinct(query, "plan", DeviceLicense.class, DeviceLicense.class); + } + + public int getValidLicenseCount(Site site) { + List licenseModels = this.getLicenseModels(site); + int validLicenseCount = 0; + + for(LicenseModel licenseModel : licenseModels) { + validLicenseCount += licenseModel.getReport().getInteger("fresh", 0) + licenseModel.getReport().getInteger("active", 0) + licenseModel.getReport().getInteger("used", 0); + } + + return validLicenseCount; + } + + public List getLicenseModels(Site site) { + List licenseModels; + if (site.isReseller()) { + List plans = this.getPlans(site); + licenseModels = new ArrayList(); + + for(Object planItem : plans) { + licenseModels.addAll(this.getLicenseModels(site, (String)planItem)); + } + } else { + licenseModels = this.getLicenseModels(site, site.getPlanName()); + } + + return licenseModels; + } + + public List getLicenseModels(Site site, String plan) { + DateTime today = new DateTime(); + Date soon = today.plusDays(10).toDate(); + Date now = new Date(); + DBRef siteRef = new DBRef("site", site.getUuid()); + Criteria criteria = Criteria.where(site.isChild() ? "childSite" : "site").is(siteRef); + if (!Strings.isNullOrEmpty(plan)) { + criteria.and("plan").is(plan); + } + + MatchOperation matchOp = Aggregation.match(criteria); + ProjectionOperation projectionOp = Aggregation.project(new String[0]).and(ObjectOperators.valueOf("licenseModel").toArray()).as("modelRef").and(ConditionalOperators.ifNull("childSite").then((Object)null)).as("childSite").and(ConditionalOperators.ifNull("deviceUuid").then((Object)null)).as("deviceUuid").and(ConditionalOperators.ifNull("activatedAt").then((Object)null)).as("activatedAt").and(ConditionalOperators.ifNull("expiry").then((Object)null)).as("expiry"); + LookupOperation lookupOp = Aggregation.lookup("licenseModel", "modelRef.1.v", "_id", "model"); + GroupOperation groupOp = Aggregation.group(new String[]{"$model._id"}).first("model").as("licenseModel").count().as("total").sum(ConditionalOperators.when(Criteria.where("childSite").is((Object)null)).then(0).otherwise(1)).as("licensed").sum(this.countCond(site, false, false, now, (Date)null)).as("fresh").sum(this.countCond(site, false, false, now, soon)).as("freshExpiring").sum(this.countCond(site, true, true, now, (Date)null)).as("active").sum(this.countCond(site, true, false, now, (Date)null)).as("inactive").sum(this.countCond(site, false, true, now, (Date)null)).as("used").sum(this.countCond(site, false, true, now, soon)).as("usedExpiring").sum(this.expiredCond(site, now, (Boolean)null)).as("expired").sum(this.expiredCond(site, today.plusDays(10).toDate(), (Boolean)null)).as("expiredIn10").sum(this.expiredCond(site, today.plusDays(30).toDate(), (Boolean)null)).as("expiredIn30").sum(this.expiredCond(site, today.plusDays(45).toDate(), (Boolean)null)).as("expiredIn45").sum(this.expiredCond(site, today.plusDays(45).toDate(), true)).as("expiredIn45WithAutoRenew").max("expiry").as("finalExpiry"); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{matchOp, projectionOp, lookupOp, groupOp}); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceLicense.class, Document.class); + List licenseModels = new ArrayList(); + results.forEach((result) -> { + List modelList = result.getList("licenseModel", Document.class); + if (modelList != null && !modelList.isEmpty()) { + LicenseModel model = (LicenseModel)this.convertToObject(LicenseModel.class, (Document)modelList.get(0)); + if (model != null) { + licenseModels.add(model); + if (!Strings.isNullOrEmpty(plan)) { + model.setReport("plan", plan); + } + + model.setReport("total", result.get("total")); + model.setReport("fresh", result.get("fresh")); + model.setReport("freshExpiring", result.get("freshExpiring")); + model.setReport("active", result.get("active")); + model.setReport("inactive", result.get("inactive")); + model.setReport("used", result.get("used")); + model.setReport("usedExpiring", result.get("usedExpiring")); + model.setReport("expired", result.get("expired")); + if (site.isReseller()) { + model.setReport("licensed", result.get("licensed")); + } + + model.setReport("expiredIn10", result.get("expiredIn10")); + model.setReport("expiredIn30", result.get("expiredIn30")); + model.setReport("expiredIn45", result.get("expiredIn45")); + model.setReport("expiredIn45WithAutoRenew", result.get("expiredIn45WithAutoRenew")); + model.setReport("finalExpiry", result.get("finalExpiry")); + } + } + + }); + return licenseModels; + } + + private ConditionalOperators.Cond countCond(Site site, Boolean deviceExists, Boolean isActivated, Date from, Date to) { + List conds = new ArrayList(); + if (site.isReseller()) { + conds.add(Criteria.where("childSite").is((Object)null)); + } + + if (deviceExists) { + conds.add(Criteria.where("deviceUuid").ne((Object)null)); + } else { + conds.add(Criteria.where("deviceUuid").is((Object)null)); + } + + if (isActivated) { + conds.add(Criteria.where("activatedAt").ne((Object)null)); + } else { + conds.add(Criteria.where("activatedAt").is((Object)null)); + } + + List periodConds = new ArrayList(); + if (from != null) { + periodConds.add(Criteria.where("expiry").gt(from)); + } + + if (to != null) { + periodConds.add(Criteria.where("expiry").lt(to)); + } + + if (from != null && to != null) { + conds.add((new Criteria()).andOperator(periodConds)); + } else { + conds.add(Criteria.where("expiry").gt(from)); + } + + return ConditionalOperators.when((new Criteria()).andOperator(conds)).then(1).otherwise(0); + } + + private ConditionalOperators.Cond expiredCond(Site site, Date to, Boolean isAutoRenew) { + List conds = new ArrayList(); + if (site.isReseller()) { + conds.add(Criteria.where("childSite").is((Object)null)); + } + + conds.add(Criteria.where("expiry").ne((Object)null)); + conds.add(Criteria.where("expiry").lt(to)); + if (isAutoRenew != null) { + conds.add(Criteria.where("autoRenew").is(isAutoRenew)); + } + + return ConditionalOperators.when((new Criteria()).andOperator(conds)).then(1).otherwise(0); + } + + public List getSiteLicenses(UUID siteUuid, UUID licenseModelUuid) { + LicenseModel licenseModel = this.licenseService.findLicenseModelByUuid(licenseModelUuid); + if (licenseModel == null) { + return null; + } else if (licenseModel.getType() == 't') { + SiteLicense license = new SiteLicense(); + license.setLicenseModel(licenseModel); + List licenses = new ArrayList(); + licenses.add(license); + return licenses; + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return new ArrayList(); + } else { + Query query = Query.query(Criteria.where("site.$id").is(siteUuid).and("licenseModel.$id").is(licenseModelUuid).and("enabled").is(true)); + return this.mongoTemplate.find(query, SiteLicense.class); + } + } + } + + public LicenseModel getTrialLicense() { + return this.licenseService.getTrialLicenseModel(); + } + + public void unsetNullChildSiteReference(Site site) { + Query query = new Query(); + query.addCriteria(Criteria.where("site.$id").is(site.getUuid()).and("childSite").exists(true)); + + for(SiteLicense license : this.mongoTemplate.find(query, SiteLicense.class)) { + if (license.getChildSite() == null) { + this.mongoTemplate.updateMulti(Query.query(Criteria.where("_id").is(license.getUuid())), (new Update()).unset("childSite"), SiteLicense.class); + } + } + + } + + public Page find(Site site, boolean isLicensed, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + if (site != null) { + if (site.isChild()) { + query.addCriteria(Criteria.where("site.$id").is(site.getReseller().getUuid()).and("childSite.$id").is(site.getUuid())); + } else { + if (isLicensed) { + this.unsetNullChildSiteReference(site); + } + + query.addCriteria(Criteria.where("site.$id").is(site.getUuid()).and("childSite").exists(isLicensed)); + } + } else { + query.addCriteria(Criteria.where("childSite").exists(false)); + } + + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, SiteLicense.class); + Pageable pageable = PageRequest.of(page, size); + query.with(pageable); + List result = this.mongoTemplate.find(query, SiteLicense.class); + + for(SiteLicense license : result) { + this.updateReport(license); + } + + Page pageResult = PageableExecutionUtils.getPage(result, pageable, McMongoUtils.toTotalSupplier(total)); + return pageResult; + } + + public List find(Site site, boolean isLicensed, JsonObject filter, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + if (site != null) { + if (site.isChild()) { + query.addCriteria(Criteria.where("site.$id").is(site.getReseller().getUuid()).and("childSite.$id").is(site.getUuid())); + } else { + query.addCriteria(Criteria.where("site.$id").is(site.getUuid()).and("childSite").exists(isLicensed)); + } + } else { + query.addCriteria(Criteria.where("childSite").exists(false)); + } + + List result = this.mongoTemplate.find(query, SiteLicense.class); + + for(SiteLicense license : result) { + this.updateReport(license); + } + + Iterator it = result.iterator(); + + while(it.hasNext()) { + SiteLicense license = (SiteLicense)it.next(); + if (license.getSite() == null) { + this.deleteById(SiteLicense.class, license.getUuid()); + it.remove(); + } + } + + return result; + } + + private void updateReport(SiteLicense license) { + long fresh = 0L; + long active = 0L; + long inactive = 0L; + long used = 0L; + long licensed = 0L; + long expired = 0L; + Date now = new Date(); + fresh = this.licenseCount(license, false, false, now); + active = this.licenseCount(license, true, true, now); + inactive = this.licenseCount(license, true, false, now); + used = this.licenseCount(license, false, true, now); + Query query = this.licenseQuery(license); + query.addCriteria(Criteria.where("expiry").lt(now)); + expired = this.mongoTemplate.count(query, DeviceLicense.class); + if (!license.isForChildSite() && license.getSite() != null && license.getSite().isReseller()) { + query = new Query(Criteria.where("siteLicense.$id").is(license.getUuid()).and("childSite").exists(true)); + licensed = this.mongoTemplate.count(query, DeviceLicense.class); + } + + license.setReport("fresh", fresh); + license.setReport("active", active); + license.setReport("inactive", inactive); + license.setReport("used", used); + license.setReport("licensed", licensed); + license.setReport("expired", expired); + } + + private Query licenseQuery(SiteLicense license) { + Query query = new Query(); + if (license.isForChildSite()) { + query.addCriteria(Criteria.where("childSiteLicense.$id").is(license.getUuid())); + } else { + query.addCriteria(Criteria.where("siteLicense.$id").is(license.getUuid()).and("childSite").exists(false)); + } + + return query; + } + + private Long licenseCount(SiteLicense license, boolean deviceExits, boolean isActivated, Date now) { + Query query = this.licenseQuery(license); + query.addCriteria(Criteria.where("deviceUuid").exists(deviceExits).and("activatedAt").exists(isActivated)); + if (!license.isPerpetual() || !isActivated) { + query.addCriteria(Criteria.where("expiry").gte(now)); + } + + return this.mongoTemplate.count(query, DeviceLicense.class); + } + + public Document getExpiringCount(UUID siteLicenseUuid, Date checkDateTime) { + Document facedOp = new Document("$facet", (new Document("nearestExpired", Arrays.asList(new Document("$match", new Document("_id.expiry", new Document("$lte", checkDateTime))), new Document("$limit", 1), new Document("$addFields", new Document("_id", "$_id.expiry"))))).append("upcomingExpiration", Arrays.asList(new Document("$match", new Document("_id.expiry", new Document("$gt", checkDateTime))), new Document("$sort", new Document("_id.expiry", 1)), new Document("$limit", 1), new Document("$addFields", new Document("_id", "$_id.expiry"))))); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match((new Criteria()).andOperator(new Criteria[]{Criteria.where("childSiteLicense.$id").is(siteLicenseUuid)})), Aggregations.newOperation("{$group: {'_id':{expiry:'$expiry'}, 'count':{$sum:1}}}"), Aggregations.newOperation("{$sort:{'_id.expiry':-1}}"), Aggregations.newOperation(facedOp)}).withOptions(Aggregation.newAggregationOptions().collation(LocaleConst.COLLATION_DEFAULT).build()); + return (Document)this.mongoTemplate.aggregate(aggregation, DeviceLicense.class, Document.class).getUniqueMappedResult(); + } + + public void deleteSiteLicense(SiteLicense license) { + if (!this.isLicenseUsed(license.getUuid())) { + this.deleteById(SiteLicense.class, license.getUuid()); + } + + } + + public void deleteSiteLicense(UUID licenseUuid) { + if (!this.isLicenseUsed(licenseUuid)) { + this.deleteById(SiteLicense.class, licenseUuid); + } + + } + + public boolean isAnySiteLicenseUsed(UUID modelUuid) { + Query query = Query.query(Criteria.where("licenseModel.$id").is(modelUuid)); + return this.mongoTemplate.exists(query, SiteLicense.class); + } + + public boolean isLicenseUsed(UUID licenseUuid) { + return true; + } + + public boolean isNormal(Date expiry) { + return expiry.after(new Date()); + } + + public boolean isTrial(Date expiry) { + Date now = new Date(); + return expiry.before(now) && (new DateTime(expiry)).plusDays(45).toDate().after(now); + } + + public boolean isLocked(Date expiry) { + Date now = new Date(); + return (new DateTime(expiry)).plusDays(45).toDate().before(now) && (new DateTime(expiry)).plusDays(90).toDate().after(now); + } + + public boolean needToRemove(Date expiry) { + Date now = new Date(); + return (new DateTime(expiry)).plusDays(90).toDate().before(now); + } + + public int touchChildLicenses() { + Query queryDeviceLicense = Query.query(Criteria.where("childSite").exists(true).and("childSiteLicense").exists(false)); + List licenses = this.mongoTemplate.find(queryDeviceLicense, DeviceLicense.class); + + for(DeviceLicense license : licenses) { + Query querySiteLicense = Query.query(Criteria.where("childSite.$id").is(license.getChildSite().getUuid()).and("licenseModel.$id").is(license.getLicenseModel())); + List siteLicenses = this.mongoTemplate.find(querySiteLicense, SiteLicense.class); + if (siteLicenses.size() == 1) { + SiteLicense siteLicense = (SiteLicense)siteLicenses.get(0); + license.setChildSiteLicense(siteLicense); + this.saveDocument(license); + } else if (siteLicenses.size() > 1) { + for(SiteLicense siteLicense : siteLicenses) { + Query query = new Query(Criteria.where("childSiteLicense.$id").is(siteLicense.getUuid())); + long appliedCount = this.mongoTemplate.count(query, DeviceLicense.class); + if (appliedCount == 0L || appliedCount < (long)siteLicense.getAmount()) { + license.setChildSiteLicense(siteLicense); + this.saveDocument(license); + break; + } + } + } + } + + return licenses.size(); + } + + public void sendMessageToRecipients(SiteLicense siteLicense) { + Site site = siteLicense.getChildSite() != null ? siteLicense.getChildSite() : siteLicense.getSite(); + NewsMessage message = new NewsMessage(); + message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); + message.setCategory("site_license"); + message.setForWhat("Site license requested"); + String title = "[Site License]"; + String format = "Site License requested at %s"; + message.getReference().put("siteIdName", site.getIdName()); + title = title + " Requested"; + format = format + " by." + site.getIdName(); + message.getMessage("en-US").put("title", title); + String content = String.format(format, (new SimpleDateFormat()).format(siteLicense.getCreated())); + message.getMessage("en-US").put("content", content); + message.getMessage("en-US").put("summary", content); + this.newsMessageService.save(message); + List supervisors = this.userService.findSupervisors(site.getUuid()); + String plan = site.getShowPlanName(siteLicense.getPlan()); + String licenseModel = siteLicense.getLicenseModel().getName(); + long amount = (long)siteLicense.getAmount(); + if (site.isChild()) { + supervisors.forEach((supervisor) -> { + this.sendMessageToRecipients(supervisor.getEmail(), message, plan, licenseModel, amount); + this.newsMessageService.setMessageLog(message, supervisor, site); + if (this.sessionManager.isOnline(supervisor.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)supervisor, 108); + } + + }); + } else { + InternetAddress[] recipients = this.settingsService.siteRequestRecipients(); + if (recipients != null) { + for(InternetAddress user : recipients) { + this.sendMessageToRecipients(user.getAddress(), message, plan, licenseModel, amount); + } + } + } + + } + + public void sendMessageToRecipients(String email, NewsMessage message, String plan, String licenseModel, long amount) { + if (email != null) { + message.getReference().put("plan", plan); + message.getReference().put("licenseModel", licenseModel); + message.getReference().put("amount", amount); + this.emailService.sendSiteLicenseRequestNoti(email, message); + } + } + + public void sendMessage(SiteLicense siteLicense) { + Site site = siteLicense.getChildSite() != null ? siteLicense.getChildSite() : siteLicense.getSite(); + NewsMessage message = new NewsMessage(); + message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); + message.setCategory("site_license"); + message.setForWhat("Site license generated"); + String title = "[Site License]"; + String format = "Site license requested at %s"; + message.getReference().put("siteIdName", site.getIdName()); + title = title + " Generated"; + format = format + " generated successfully."; + message.getMessage("en-US").put("title", title); + String content = String.format(format, (new SimpleDateFormat()).format(siteLicense.getCreated())); + message.getMessage("en-US").put("content", content); + message.getMessage("en-US").put("summary", content); + this.newsMessageService.save(message); + List users = this.userService.findSupervisors(site.getUuid()); + String plan = site.getShowPlanName(siteLicense.getPlan()); + String licenseModel = siteLicense.getLicenseModel().getName(); + long amount = (long)siteLicense.getAmount(); + users.forEach((user) -> this.sendMessage(user, message, site, plan, licenseModel, amount)); + } + + public void sendMessage(User user, NewsMessage message, Site site, String plan, String licenseModel, long amount) { + if (user.getEnabled()) { + this.newsMessageService.setMessageLog(message, user, site); + if (this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)user, 109); + } + + message.getReference().put("plan", plan); + message.getReference().put("licenseModel", licenseModel); + message.getReference().put("amount", amount); + this.emailService.sendSiteLicenseNoti(user, message); + } + } +} diff --git a/src/main/java/com/midm/service/org/SiteService.java b/src/main/java/com/midm/service/org/SiteService.java new file mode 100644 index 0000000..2128635 --- /dev/null +++ b/src/main/java/com/midm/service/org/SiteService.java @@ -0,0 +1,798 @@ +package com.midm.service.org; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceLicense; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.DeviceProfileGroup; +import com.midm.model.file.AppFile; +import com.midm.model.file.BaseFile; +import com.midm.model.file.OtaFile; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.Site; +import com.midm.model.org.SiteInfo; +import com.midm.model.org.SiteRequest; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.DeviceService; +import com.midm.service.device.ProfileService; +import com.midm.service.file.FileService; +import com.midm.service.log.LogService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.news.NewsMessageService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.LicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.AggregateIterable; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.result.UpdateResult; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import javax.mail.internet.InternetAddress; +import org.bson.Document; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.AddFieldsOperation; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.aggregation.GroupOperation; +import org.springframework.data.mongodb.core.aggregation.LookupOperation; +import org.springframework.data.mongodb.core.aggregation.MatchOperation; +import org.springframework.data.mongodb.core.aggregation.ObjectOperators; +import org.springframework.data.mongodb.core.aggregation.ProjectionOperation; +import org.springframework.data.mongodb.core.aggregation.ArrayOperators.ArrayElemAt; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +@Service +public class SiteService extends BaseService { + @Autowired + @Lazy + private DeviceService deviceService; + @Autowired + @Lazy + private UserService userService; + @Autowired + @Lazy + private ProfileService profileService; + @Autowired + @Lazy + @Qualifier("fileService") + private FileService fileService; + @Autowired + private LogService logService; + @Autowired + private SettingsService settingsService; + @Autowired + private EmailService emailService; + @Autowired + private NewsMessageService newsMessageService; + @Autowired + @Lazy + private HostLicenseService hostLicenseService; + @Autowired + @Lazy + private LicenseService licenseService; + @Autowired + private WebSocketSessionManager sessionManager; + @Autowired + @Lazy + private SiteLicenseService siteLicenseService; + @Autowired + @Lazy + private CloudStorageService cloudStorageService; + private static Map sites = new HashMap(); + + public boolean hasSite() { + return this.count(Site.class) > 0L; + } + + public Site save(Site site) { + if (site == null) { + return null; + } else { + if (site.getUuid() == null) { + site.init(); + } + + boolean blockAllowed = site.getSettingAsBoolean("device", "blockAllowed", false); + this.deviceService.setBlockAllowed(site.getUuid(), blockAllowed); + site.setUpdated(); + site = (Site)this.saveDocument(site); + sites.put(site.getUuid(), site); + return site; + } + } + + public void enableSites(List siteUuids, boolean enabled) { + Query query = Query.query(Criteria.where("_id").in(siteUuids)); + Update update = Update.update("enabled", enabled); + this.mongoTemplate.updateMulti(query, update, Site.class); + siteUuids.forEach((siteUuid) -> { + Site site = this.findByUuid(siteUuid); + if (site != null) { + site.setEnabled(enabled); + } + + }); + } + + public UpdateResult updatePlan(UUID siteUuid, String plan) { + if (Strings.isNullOrEmpty(plan)) { + return null; + } else { + Query query = Query.query(Criteria.where("_id").is(siteUuid)); + Update update = Update.update("profile.plan.plan", plan); + update.unset("profile.plan.upgradeStatus"); + update.unset("profile.plan.targetPlan"); + if (!plan.equals("lite")) { + update.unset("profile.plan.features"); + } + + UpdateResult result = this.mongoTemplate.updateFirst(query, update, Site.class); + this.updateSiteMap(siteUuid, result); + return result; + } + } + + public UpdateResult setSetting(UUID siteUuid, DbObject settings) { + if (settings != null && !settings.isEmpty()) { + Query query = Query.query(Criteria.where("_id").is(siteUuid)); + Update update = new Update(); + settings.forEach((key, value) -> { + if (value != null && !value.equals("")) { + update.set("settings." + key, value); + } else { + update.unset("settings." + key); + } + + }); + boolean blockAllowed = settings.getDbObject(new String[]{"device"}).getBoolean("blockAllowed", false); + this.deviceService.setBlockAllowed(siteUuid, blockAllowed); + UpdateResult result = this.mongoTemplate.updateFirst(query, update, Site.class); + this.updateSiteMap(siteUuid, result); + String dataUsage = settings.getDbObject(new String[]{"report"}).getString("dataUsage", "none"); + if (!dataUsage.equals("none")) { + Update updateDataUsage = Update.update("updated", new Date()); + updateDataUsage.unset("settings.network.mobile.report").unset("status.data_usage"); + this.mongoTemplate.updateMulti(Query.query(Criteria.where("siteUuid").is(siteUuid)), updateDataUsage, DeviceProfile.class); + } + + return result; + } else { + return null; + } + } + + public UpdateResult updateProfile(UUID siteUuid, DbObject profile) { + if (profile != null && !profile.isEmpty()) { + Query query = Query.query(Criteria.where("_id").is(siteUuid)); + Update update = Update.update("profile", profile); + UpdateResult result = this.mongoTemplate.updateFirst(query, update, Site.class); + this.updateSiteMap(siteUuid, result); + return result; + } else { + return null; + } + } + + public UpdateResult setSetting(UUID siteUuid, String key, Object value) { + Query query = Query.query(Criteria.where("_id").is(siteUuid)); + Update update = Update.update("settings." + key, value); + UpdateResult result = this.mongoTemplate.updateFirst(query, update, Site.class); + this.updateSiteMap(siteUuid, result); + return result; + } + + private void updateSiteMap(UUID siteUuid, UpdateResult result) { + if (result.getModifiedCount() > 0L) { + Site site = (Site)this.findById(Site.class, siteUuid); + if (site != null) { + sites.put(siteUuid, site); + } + } + + } + + public Site find(User user, UUID siteUuid, String siteId) { + Site site = null; + if (siteUuid != null) { + site = this.findByUuid(siteUuid); + } + + if (site == null && !Strings.isNullOrEmpty(siteId)) { + site = this.findByIdName(siteId); + } + + if (site == null) { + site = this.findByUuid(user.getSiteUuid()); + } + + return site; + } + + public Site findByIdName(String idName) { + Query query = Query.query(Criteria.where("idName").is(idName)); + Site site = (Site)this.mongoTemplate.findOne(query, Site.class); + if (site != null) { + sites.put(site.getUuid(), site); + } + + return site; + } + + public Site findByCredential(String credentail) { + Query query = Query.query(Criteria.where("settings.credential.credential").is(credentail)); + Site site = (Site)this.mongoTemplate.findOne(query, Site.class); + if (site != null) { + sites.put(site.getUuid(), site); + } + + return site; + } + + public UpdateResult updateCredential(UUID siteUuid, DbObject credential) { + return this.setSetting(siteUuid, "credential", credential); + } + + public Site findByUuid(UUID siteUuid) { + Site site = null; + if (siteUuid != null) { + if (sites.containsKey(siteUuid)) { + site = (Site)sites.get(siteUuid); + } else { + site = (Site)this.findById(Site.class, siteUuid); + if (site != null) { + sites.put(siteUuid, site); + } + } + } + + return site; + } + + public boolean reorganize(String id, String resellerId, String reorganize) { + Site site = Strings.isNullOrEmpty(id) ? null : this.findByIdName(id); + if (site == null) { + return false; + } else { + Site resellerSite = Strings.isNullOrEmpty(id) ? null : this.findByIdName(resellerId); + if (resellerSite == null) { + return false; + } else { + if (reorganize.equals("toChild")) { + if (site.isChild() || site.isReseller()) { + return false; + } + + site.setReseller(resellerSite); + } else if (reorganize.equals("toNormal")) { + if (!site.isChild()) { + return false; + } + + site.setReseller((Site)null); + } + + this.save(site); + if (sites.containsKey(site.getUuid())) { + sites.remove(site.getUuid()); + sites.put(site.getUuid(), site); + } + + return true; + } + } + } + + public Site findByModelAndUser(String model, User user) { + if (!Strings.isNullOrEmpty(model) && user != null) { + for(SiteInfo siteInfo : user.getSites()) { + Site site = this.findByUuid(siteInfo.getSiteUuid()); + if (model.equals(site.getModel())) { + return site; + } + } + + return null; + } else { + return null; + } + } + + public String getTitle(UUID siteUuid) { + Site site = this.findByUuid(siteUuid); + if (site == null) { + return null; + } else { + StringBuilder builder = new StringBuilder(); + if (site.isChild()) { + builder.append(site.getReseller().getTitle()); + builder.append("/"); + } + + builder.append(site.getTitle()); + return builder.toString(); + } + } + + public boolean exists(UUID siteUuid) { + return sites.containsKey(siteUuid) || this.existsById(Site.class, siteUuid); + } + + public boolean exists(String siteId) { + return this.mongoTemplate.exists(Query.query(Criteria.where("idName").regex(String.format("^%s$", siteId), "i")), Site.class); + } + + public List getByPlan(String plan) { + return this.mongoTemplate.find(Query.query(Criteria.where("profile.plan.plan").regex(String.format("^%s$", plan), "i")), Site.class); + } + + public boolean hasBatteryPlan(UUID siteUuid) { + Site site = this.findByUuid(siteUuid); + return site != null ? site.isStandardWithBatteryPro() : false; + } + + public Page findAdminState(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + Page pageResult = this.findByPage(Site.class, filter, sortBy, direction, page, size); + + for(Site site : pageResult) { + long deviceNumbers = this.deviceService.getDeviceCount(site.getUuid()); + long deviceEnrolled = this.deviceService.getDeviceStat(site.getUuid(), (String)null, "enrolled"); + long deviceOnline = this.deviceService.getDeviceStat(site.getUuid(), (String)null, "online"); + long deviceDisabled = this.deviceService.getDeviceStat(site.getUuid(), (String)null, "disabled"); + long childDeviceNumbers = 0L; + long childSiteNumbers = 0L; + site.setProfile("report", "deviceNumbers", deviceNumbers); + site.setProfile("report", "deviceEnrolled", deviceEnrolled); + site.setProfile("report", "deviceRegister", deviceNumbers - deviceEnrolled); + site.setProfile("report", "deviceEnabled", deviceNumbers - deviceDisabled); + site.setProfile("report", "deviceDisabled", deviceDisabled); + site.setProfile("report", "deviceOnline", deviceOnline); + site.setProfile("report", "deviceOffline", deviceNumbers - deviceOnline); + if (!this.hostLicenseService.isStandalone() && site.isReseller()) { + childDeviceNumbers = this.deviceService.getChildDeviceCount(site); + childSiteNumbers = this.getChildSiteCount(site.getUuid()); + site.setProfile("report", "childDeviceNumbers", childDeviceNumbers); + site.setProfile("report", "childSiteNumbers", childSiteNumbers); + } + + long userNumbers = this.userService.getUserCount(site.getUuid()); + site.setProfile("report", "userNumbers", userNumbers); + if (!this.hostLicenseService.isStandalone()) { + List licenseModels = this.siteLicenseService.getLicenseModels(site, site.getPlanName()); + site.setProfile("report", "licenseModels", licenseModels); + } + } + + return pageResult; + } + + public long getChildSiteCount(UUID siteUuid) { + return this.mongoTemplate.count(Query.query(Criteria.where("reseller.$id").is(siteUuid)), Site.class); + } + + public List getChildSite(UUID siteUuid) { + return this.mongoTemplate.find(Query.query(Criteria.where("reseller.$id").is(siteUuid)), Site.class); + } + + public PageImpl findchildState(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction, Integer page, Integer size) { + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + query.addCriteria(Criteria.where("reseller").exists(true)).with(Sort.by(new String[]{"reseller.$id"})); + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, entityClass); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), entityClass); + return new PageImpl(result, pageable, total); + } + + public Page childState(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + Page pageResult = this.findchildState(Site.class, filter, sortBy, direction, page, size); + + for(Site childSite : pageResult) { + List childSiteUsers = this.userService.findUser(childSite.getUuid()); + childSite.setProfile("report", "users", childSiteUsers); + List childSitelicenseModels = this.siteLicenseService.getLicenseModels(childSite, childSite.getPlanName()); + childSite.setProfile("report", "licenseModels", childSitelicenseModels); + long childDeviceNumbers = this.deviceService.getDeviceCount(childSite.getUuid()); + childSite.setProfile("deviceNumbers", childDeviceNumbers); + } + + return pageResult; + } + + public Document totalState() { + Document stateCollection = new Document(); + long siteRegister = this.mongoTemplate.count(Query.query(Criteria.where("reseller").exists(false)), Site.class); + long siteEnabled = this.mongoTemplate.count(Query.query(Criteria.where("reseller").exists(false).and("enabled").is(true)), Site.class); + long siteDisabled = siteRegister - siteEnabled; + long childSites = this.mongoTemplate.count(Query.query(Criteria.where("reseller").exists(true)), Site.class); + stateCollection.put("total_sites", siteRegister); + stateCollection.put("total_sites_enabled", siteEnabled); + stateCollection.put("total_sites_disabled", siteDisabled); + stateCollection.put("total_devices", this.deviceService.count(Device.class)); + if (!this.settingsService.isStandalone()) { + stateCollection.put("total_sub_sites", childSites); + LicenseModel triaLicenseModel = this.licenseService.findLicenseModelByIdName("trial"); + long totalAmount = this.mongoTemplate.count(Query.query(Criteria.where("licenseModel.$id").ne(triaLicenseModel.getUuid())), DeviceLicense.class); + stateCollection.put("total_device_license", totalAmount); + } + + return stateCollection; + } + + public List getTotalLicenseCount() { + LicenseModel triaLicenseModel = this.licenseService.findLicenseModelByIdName("trial"); + List pipeline = Arrays.asList(new Document("$match", new Document("licenseModel.$id", new Document("$ne", triaLicenseModel.getUuid()))), new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$licenseModel"), 1)))), new Document("$lookup", (new Document("from", "licenseModel")).append("foreignField", "_id").append("localField", "licenseModel.v").append("as", "licenseModel")), new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList("$licenseModel", 0)))), new Document("$group", (new Document("_id", "$licenseModel._id")).append("name", new Document("$first", "$licenseModel.name")).append("idName", new Document("$first", "$licenseModel.idName")).append("count", new Document("$sum", 1)))); + List licenseCounts = new ArrayList(); + AggregateIterable results = this.getCollection(DeviceLicense.class).aggregate(pipeline); + MongoCursor var5 = results.iterator(); + + while(var5.hasNext()) { + Document result = (Document)var5.next(); + licenseCounts.add(result); + } + + return licenseCounts; + } + + public boolean isValid(UUID siteUuid) { + Site site = this.findByUuid(siteUuid); + return site != null && site.getEnabled(); + } + + public List findAll(Site site, String model, String plan, String sortBy, boolean updateReport) { + Criteria criteria = new Criteria(); + if (site == null) { + criteria.and("reseller").exists(false); + } else { + criteria.and("reseller.$id").is(site.getUuid()); + } + + if (!Strings.isNullOrEmpty(model)) { + criteria.and("profile.model").is(model); + } + + if (!Strings.isNullOrEmpty(plan)) { + criteria.and("profile.plan.plan").is(plan); + } + + Query query = Query.query(criteria); + if (!Strings.isNullOrEmpty(sortBy)) { + Sort sort = Sort.by(Sort.DEFAULT_DIRECTION, new String[]{sortBy}); + query.with(sort); + } + + List sites = this.mongoTemplate.find(query, Site.class); + if (updateReport) { + for(Site siteItem : sites) { + this.updateLicenseReport(siteItem); + this.updateLatestVisit(siteItem); + } + } + + return sites; + } + + public List findAllChilds(Site parentSite) { + Query query = Query.query(Criteria.where("reseller.$id").is(parentSite.getUuid())); + return this.mongoTemplate.find(query, Site.class); + } + + public void sendMessageToRecipients(Site site) { + NewsMessage message = new NewsMessage(); + message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); + message.setCategory("site_upgrade"); + message.setForWhat("Site upgrade requested"); + String title = "[Site Upgrade]"; + String format = "Site Upgrade requested at %s"; + message.getReference().put("siteIdName", site.getIdName()); + title = title + " Requested"; + format = format + " by." + site.getIdName(); + message.getMessage("en-US").put("title", title); + String content = String.format(format, (new SimpleDateFormat()).format(site.getUpdated())); + message.getMessage("en-US").put("content", content); + message.getMessage("en-US").put("summary", content); + this.newsMessageService.save(message); + List supervisors = this.userService.findSupervisors(site.getUuid()); + String plan = site.getShowPlanName(site.getPlanName()); + String targetPlan = site.getShowPlanName(site.getUpgradeTargetPlan()); + Date requestDate = site.getUpdated(); + if (site.isChild()) { + supervisors.forEach((supervisor) -> { + this.sendMessageToRecipients(supervisor.getEmail(), message, plan, targetPlan, requestDate); + this.newsMessageService.setMessageLog(message, supervisor, site); + if (this.sessionManager.isOnline(supervisor.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)supervisor, 107); + } + + }); + } else { + InternetAddress[] recipients = this.settingsService.siteRequestRecipients(); + if (recipients != null) { + for(InternetAddress user : recipients) { + this.sendMessageToRecipients(user.getAddress(), message, plan, targetPlan, requestDate); + } + } + } + + } + + public void sendMessageToRecipients(String email, NewsMessage message, String plan, String targetPlan, Date requestDate) { + if (email != null) { + message.getReference().put("plan", plan); + message.getReference().put("targetPlan", targetPlan); + message.getReference().put("requestDate", requestDate); + this.emailService.sendSiteUpgradeRequestNoti(email, message); + } + } + + public void sendMessage(Site site, String targetPlan) { + NewsMessage message = new NewsMessage(); + message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); + message.setCategory("site_upgrade"); + message.setForWhat("Site upgrade success"); + String title = "[Site Upgrade]"; + String format = "Site upgrade requested at %s"; + message.getReference().put("siteIdName", site.getIdName()); + title = title + " Upgrade"; + format = format + " upgrade ready."; + message.getMessage("en-US").put("title", title); + String content = String.format(format, (new SimpleDateFormat()).format(site.getUpdated())); + message.getMessage("en-US").put("content", content); + message.getMessage("en-US").put("summary", content); + this.newsMessageService.save(message); + List users = this.userService.findSupervisors(site.getUuid()); + users.forEach((user) -> this.sendMessage(user, message, site, site.getShowPlanName(site.getPlanName()), site.getShowPlanName(targetPlan))); + } + + public void sendMessage(User user, NewsMessage message, Site site, String plan, String targetPlan) { + if (user.getEnabled()) { + this.newsMessageService.setMessageLog(message, user, site); + if (this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)user, 106); + } + + message.getReference().put("plan", plan); + message.getReference().put("targetPlan", targetPlan); + this.emailService.sendSiteUpgradeNoti(user, message); + } + } + + public List getUserSites(User user) { + List siteInfos = user.getSites(); + if (siteInfos.size() > 0) { + List siteUuids = new ArrayList(); + Criteria criteria = Criteria.where("enabled").is(true); + + for(SiteInfo siteInfo : siteInfos) { + if (siteInfo.isEnabled()) { + siteUuids.add(siteInfo.getSiteUuid()); + } + } + + if (siteUuids.size() > 0) { + criteria.and("_id").in(siteUuids); + Query query = Query.query(criteria).collation(LocaleConst.COLLATION_DEFAULT).with(Sort.by(Direction.ASC, new String[]{"profile.name"})); + query.fields().include("profile").include("reseller"); + return this.mongoTemplate.find(query, Site.class); + } + } + + return new ArrayList(); + } + + public void updateLatestVisit(Site site) { + Date latestVisit = site.getUpdated(); + Device device = this.deviceService.findLastestVisit(site.getUuid()); + if (device != null && latestVisit.before(device.getUpdated())) { + latestVisit = device.getUpdated(); + } + + site.setLatestVisit(latestVisit); + } + + public Page find(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + Page pageResult = this.findByPage(Site.class, filter, sortBy, direction, page, size); + + for(Site site : pageResult) { + long deviceNumbers = this.deviceService.getDeviceCount(site.getUuid()); + site.setProfile("deviceNumbers", deviceNumbers); + if (site.isReseller()) { + long childDeviceNumbers = this.deviceService.getChildDeviceCount(site); + site.setProfile("childDeviceNumbers", childDeviceNumbers); + } + + this.updateLatestVisit(site); + } + + return pageResult; + } + + public void delete(final Site site, final User logUser) { + this.taskExecutor.submit(new Runnable() { + public void run() { + SiteService.this.deleteAsync(site.getUuid(), logUser); + Site parentSite = site.getReseller(); + if (parentSite != null) { + SiteService.this.logService.save(logUser, parentSite.getUuid(), "activity", String.format("Child site has been removed: %s", site.getIdName())); + } else { + SiteService.this.logService.save(logUser, site.getUuid(), "activity", String.format("Site has been removed: %s", site.getIdName())); + } + + } + }); + } + + public void deleteAsync(UUID siteUuid, User logUser) { + this.deleteById(Site.class, siteUuid); + sites.remove(siteUuid); + this.deviceService.deleteBySite(siteUuid); + List users = this.userService.findUsersBySite(siteUuid); + users.forEach((user) -> this.userService.deleteSite(user, siteUuid)); + this.userService.deleteUserGroupBySiteUuid(siteUuid); + List apps = this.fileService.findApps(siteUuid, (JsonObject)null, (String)null, (Sort.Direction)null); + apps.forEach((app) -> this.fileService.deleteApp(siteUuid, app.getFileUuid())); + List files = this.fileService.findFiles(siteUuid, (JsonObject)null, (String)null, (Sort.Direction)null); + files.forEach((file) -> this.fileService.delete(siteUuid, file)); + List otas = this.fileService.findOtas((UUID)siteUuid, (JsonObject)null, (String)null, (Sort.Direction)null); + otas.forEach((ota) -> this.fileService.delete(siteUuid, ota)); + List deviceProfiles = this.profileService.findAllBySiteUuid(siteUuid); + deviceProfiles.forEach((deviceProfile) -> this.logService.clearAllLogsFor(deviceProfile.getUuid())); + this.profileService.deleteProfileBySiteUuid(siteUuid); + List deviceProfileGroups = this.profileService.findAllGroupBySiteUuid(siteUuid); + deviceProfileGroups.forEach((deviceProfileGroup) -> this.logService.clearAllLogsFor(deviceProfileGroup.getUuid())); + this.profileService.deleteProfileGroupBySiteUuid(siteUuid); + this.logService.clearAllLogsFor(siteUuid); + this.hostLicenseService.deleteStandaloneLicense(siteUuid); + this.siteLicenseService.deleteBySite(siteUuid); + String siteFilePath = Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid, new Object[0]); + (new McFile(siteFilePath)).delete(); + if (this.cloudStorageService.hasCloudStorage()) { + this.cloudStorageService.delete(siteUuid); + } + + } + + public boolean canManageRole(Site site, User user, Set roles) { + return roles.contains("SUPERVISOR") ? this.canManageSupervisor(site, user) : this.canManageUsers(site, user); + } + + public boolean canManageSupervisor(Site site, User user) { + if (site == null) { + return false; + } else if (site.isChild()) { + SiteInfo siteInfo = user.getSiteInfo(site); + if (siteInfo != null && siteInfo.hasRole("SUPERVISOR")) { + return true; + } else { + siteInfo = user.getSiteInfo(site.getReseller()); + return siteInfo != null && siteInfo.hasRole("SUPERVISOR"); + } + } else { + return user.hasRole(site.getUuid(), "SUPERVISOR") || user.hasSystemRole("SYSTEM_ADMIN"); + } + } + + public boolean canManageUsers(Site site, User user) { + if (site == null) { + return false; + } else if (site.isChild()) { + SiteInfo siteInfo = user.getSiteInfo(site); + if (siteInfo == null || !siteInfo.hasRole("SUPERVISOR") && !siteInfo.hasRole("USER_MANAGER")) { + siteInfo = user.getSiteInfo(site.getReseller()); + return siteInfo != null && siteInfo.hasRole("SUPERVISOR"); + } else { + return true; + } + } else { + SiteInfo siteInfo = user.getSiteInfo(site); + return siteInfo.hasRole("SUPERVISOR") || siteInfo.hasRole("USER_MANAGER") || user.hasSystemRole("SYSTEM_ADMIN"); + } + } + + public void updateLicenseReport(Site site) { + Criteria criteria = Criteria.where("site.$id").is(site.isChild() ? site.getReseller().getUuid() : site.getUuid()); + if (site.isChild()) { + criteria.and("childSite.$id").is(site.getUuid()); + } + + Query query = new Query(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"expiry"})); + DeviceLicense license = (DeviceLicense)this.mongoTemplate.findOne(query, DeviceLicense.class); + Date finalExpiry = license != null ? license.getExpiry() : (new DateTime(site.getCreated())).plusDays(45).toDate(); + site.addReport("finalExpiry", finalExpiry); + List licenseModels = this.siteLicenseService.getLicenseModels(site, site.getPlanName()); + site.addReport("licenseModels", licenseModels); + site.addReport("hasLicense", licenseModels.size() > 0); + } + + public void save(SiteRequest request) { + if (request.getUuid() == null) { + request.setUuid(UUID.randomUUID()); + } + + if (request.getRequestedAt() == null) { + request.setRequestedAt(new Date()); + } + + this.mongoTemplate.save(request); + } + + public List findUserByRole(Site site, Set roles) { + Criteria criteria = Criteria.where("enabled").is(true).and("sites").elemMatch(Criteria.where("siteUuid").is(site.getUuid()).and("roles").in(roles)); + Query query = new Query(criteria); + return this.mongoTemplate.find(query, User.class); + } + + @Async + public void clearOrphans() { + if (!this.hostLicenseService.isStandalone()) { + MatchOperation matchOp = Aggregation.match(Criteria.where("reseller").exists(true)); + AddFieldsOperation addFieldOp = Aggregation.addFields().addFieldWithValue("resellerRef", ArrayElemAt.arrayOf(ObjectOperators.valueOf("reseller").toArray()).elementAt(1)).build(); + LookupOperation lookupOp = Aggregation.lookup("site", "resellerRef.v", "_id", "resellerSite"); + MatchOperation matchNoResellerOp = Aggregation.match(Criteria.where("resellerSite").is(new Object[0])); + ProjectionOperation projectionOp = Aggregation.project(new String[0]).andExclude(new String[]{"resellerSite"}).andExclude(new String[]{"resellerRef"}); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{matchOp, addFieldOp, lookupOp, matchNoResellerOp, projectionOp}); + AggregationResults sites = this.mongoTemplate.aggregate(aggregation, Site.class, Site.class); + List siteList = sites.getMappedResults(); + if (!siteList.isEmpty()) { + siteList.forEach((sitex) -> this.delete(sitex, (User)null)); + } + } + + LookupOperation lookupOp = Aggregation.lookup("site", "siteUuid", "_id", "sites"); + MatchOperation matchOp = Aggregation.match(Criteria.where("sites").size(0)); + GroupOperation groupOp = Aggregation.group(new String[]{"$siteUuid"}); + Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{lookupOp, matchOp, groupOp}); + Class[] collections = new Class[]{AppFile.class, OtaFile.class, BaseFile.class}; + + for(Class classType : collections) { + this.mongoTemplate.remove(Query.query(Criteria.where("siteUuid").exists(false)), classType); + + for(Site site : this.mongoTemplate.aggregate(aggregation, classType, Site.class).getMappedResults()) { + this.delete(site, (User)null); + } + } + + } +} diff --git a/src/main/java/com/midm/service/org/UserSecurityService.java b/src/main/java/com/midm/service/org/UserSecurityService.java new file mode 100644 index 0000000..95f30c2 --- /dev/null +++ b/src/main/java/com/midm/service/org/UserSecurityService.java @@ -0,0 +1,25 @@ +package com.midm.service.org; + +import com.midm.model.org.User; +import java.util.ArrayList; +import java.util.Collection; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; + +public class UserSecurityService implements UserDetailsService { + private UserService userService; + + public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { + User user = this.userService.findUserByEmail(userName); + if (user != null && user.isAvailable()) { + Collection roles = new ArrayList(); + roles.add(new SimpleGrantedAuthority("ROLE_USER")); + UserDetails userDetails = new org.springframework.security.core.userdetails.User(userName, user.getPassword(), roles); + return userDetails; + } else { + throw new UsernameNotFoundException(userName + "is not available."); + } + } +} diff --git a/src/main/java/com/midm/service/org/UserService.java b/src/main/java/com/midm/service/org/UserService.java new file mode 100644 index 0000000..87ad84c --- /dev/null +++ b/src/main/java/com/midm/service/org/UserService.java @@ -0,0 +1,837 @@ +package com.midm.service.org; + +import com.google.api.client.util.Strings; +import com.google.common.base.Joiner; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.org.Site; +import com.midm.model.org.SiteInfo; +import com.midm.model.org.User; +import com.midm.model.org.UserGroup; +import com.midm.model.org.UserToken; +import com.midm.security.UserPrincipal; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.device.DeviceService; +import com.midm.service.log.LogService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McEmailUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mitac.cell.utils.McUuidUtils; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Field; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.scheduling.annotation.Async; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +public class UserService extends BaseService { + @Autowired + private SiteService siteService; + @Autowired + private PasswordEncoder passwordEncoder; + @Autowired + @Lazy + private EmailService emailService; + @Autowired + private SettingsService settingsService; + @Autowired + private LogService logService; + @Autowired + private DeviceService deviceService; + private static boolean hasUser = false; + + public boolean hasUser() { + if (!hasUser) { + hasUser = this.count(User.class) > 0L; + } + + return hasUser; + } + + public User save(User user) { + if (user != null && !Strings.isNullOrEmpty(user.getEmail())) { + user.setUpdated(); + user = (User)this.saveDocument(user); + return user; + } else { + return null; + } + } + + public void enableUsers(UUID siteUuid, List userUuids, boolean enabled) { + Query query = Query.query(Criteria.where("_id").in(userUuids).and("sites.siteUuid").is(siteUuid)); + Update update = Update.update("sites.$.enabled", enabled); + this.mongoTemplate.updateMulti(query, update, User.class); + } + + public List saveUsers(List users) { + List savedUsers = new ArrayList(); + + for(User user : users) { + User savedUser = this.save(user); + savedUsers.add(savedUser); + } + + return savedUsers; + } + + public UpdateResult changePassword(User user, String newPassword) { + user.setPassword(this.passwordEncoder.encode(newPassword)); + Update update = Update.update("password", user.getPassword()).set("updated", new Date()); + UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + this.deleteToken(user, 'P'); + return result; + } + + public User register(HttpServletRequest request, HttpServletResponse response, User user) { + String password = user.getPassword(); + user.init(); + user.encodePassword(this.passwordEncoder); + user = (User)this.saveDocument(user); + if (this.count(User.class) == 1L) { + this.settingsService.save("meta.startedFrom", new Date()); + } + + user.setPassword(password); + this.emailService.sendActivatedNotification(request, response, user); + return user; + } + + public void requestResetPassword(HttpServletRequest request, HttpServletResponse response, User user) { + UserToken token = new UserToken(user, 'P', 1800000L); + token = (UserToken)this.saveDocument(token); + this.emailService.sendPasswordResetRequest(request, response, user, token.getTokenUuid()); + } + + public boolean exists(User account) { + Query query = Query.query(Criteria.where("email").is(account.getEmail())); + return this.mongoTemplate.count(query, User.class) > 0L; + } + + public UpdateResult saveSite(User user) { + Update update = Update.update("sites", user.getSites()); + return this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + } + + public UpdateResult addSite(User user, SiteInfo siteInfo) { + Update update = (new Update()).push("sites", siteInfo); + return this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + } + + public UpdateResult deleteSite(User user, UUID siteUuid) { + if (siteUuid == null) { + return null; + } else { + if (user != null) { + this.deviceService.updateDeviceOwner(siteUuid, user, false); + } + + Criteria criteria = user == null ? new Criteria() : Criteria.where("_id").is(user.getUuid()); + Update update = new Update(); + update.pull("sites", new Document("siteUuid", siteUuid)); + return this.mongoTemplate.updateFirst(Query.query(criteria), update, User.class); + } + } + + public User activate(HttpServletRequest request, HttpServletResponse response, String base64Token) { + User user = null; + UUID tokenUuid = McUuidUtils.toUuidFromBase64(base64Token); + UserToken token = (UserToken)this.findById(UserToken.class, tokenUuid); + if (token != null && token.getTokenType() == 'A') { + UUID userUuid = token.getUserUuid(); + this.activate(userUuid); + user = (User)this.findById(User.class, userUuid); + this.deleteById(UserToken.class, tokenUuid); + this.emailService.sendActivatedNotification(request, response, user); + } + + return user; + } + + public boolean activate(UUID userUuid) { + Update update = Update.update("activated", new Date()).set("enabled", true); + return this.mongoTemplate.updateFirst(this.queryById(userUuid), update, User.class).getModifiedCount() > 0L; + } + + public boolean enable(UUID userUuid, boolean enable) { + Update update = Update.update("enabled", enable); + return this.mongoTemplate.updateFirst(this.queryById(userUuid), update, User.class).getModifiedCount() > 0L; + } + + public boolean switchSite(UUID userUuid, UUID siteUuid) { + Update update = new Update(); + if (siteUuid == null) { + update.unset("siteUuid").unset("settings.lastSite"); + } else { + update.set("siteUuid", siteUuid).set("settings.lastSite", siteUuid); + } + + UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(userUuid), update, User.class); + return result.getModifiedCount() > 0L; + } + + public long changeGroupByUuid(UUID siteUuid, UUID groupUuid, Collection users) { + Criteria criteria = Criteria.where("sites.siteUuid").is(siteUuid).and("_id").in(users); + Query query = Query.query(criteria); + Update update = new Update(); + if (groupUuid == null) { + update.unset("sites.$.groupUuid"); + } else { + update.set("sites.$.groupUuid", groupUuid); + } + + return this.mongoTemplate.updateMulti(query, update, User.class).getModifiedCount(); + } + + public long changeGroupByEmail(UUID siteUuid, UUID groupUuid, Collection emails) { + Criteria criteria = Criteria.where("sites.siteUuid").is(siteUuid).and("email").in(emails); + Query query = Query.query(criteria); + Update update = new Update(); + if (groupUuid == null) { + update.unset("sites.$.groupUuid"); + } else { + update.set("sites.$.groupUuid", groupUuid); + } + + return this.mongoTemplate.updateMulti(query, update, User.class).getModifiedCount(); + } + + public boolean changeLocale(User user, String locale) { + if (user.isSameLocale(locale)) { + return true; + } else { + Update update = Update.update("settings.language", locale).set("updated", new Date()); + UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + if (result.getModifiedCount() > 0L) { + user.setLocale(locale); + this.updateAuthorizedUser(user); + } + + return result.getModifiedCount() > 0L; + } + } + + public UpdateResult setSetting(User user, String key, String value) { + Update update = Update.update("settings." + key, value); + UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + return result; + } + + public boolean setLastPage(User user, String lastPage) { + Criteria criteria = Criteria.where("_id").is(user.getUuid()); + Update update = Update.update("updated", new Date()); + if (user.getSiteUuid() != null && !Strings.isNullOrEmpty(lastPage)) { + criteria.and("sites.siteUuid").is(user.getSiteUuid()); + if (!Strings.isNullOrEmpty(lastPage)) { + update.set("sites.$.settings.lastPage", lastPage); + } else { + update.unset("sites.$.settings.lastPage"); + } + } else if (!Strings.isNullOrEmpty(lastPage)) { + update.set("settings.lastPage", lastPage); + } else { + update.unset("settings.lastPage"); + } + + UpdateResult result = this.mongoTemplate.updateFirst(Query.query(criteria), update, User.class); + if (result.getModifiedCount() > 0L) { + user.setLastPage(lastPage); + this.updateAuthorizedUser(user); + } + + return result.getModifiedCount() > 0L; + } + + public boolean setSiteSetting(User user, String key, Object value) { + Criteria criteria = Criteria.where("_id").is(user.getUuid()).and("sites.siteUuid").is(user.getSiteUuid()); + Update update = Update.update("sites.$.settings." + key, value).set("updated", new Date()); + UpdateResult result = this.mongoTemplate.updateFirst(Query.query(criteria), update, User.class); + return result.getModifiedCount() > 0L; + } + + public boolean setPageSetting(User user, String url, DbObject settings) { + Update update = Update.update("settings.page." + url, settings); + UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + return result.getModifiedCount() > 0L; + } + + public boolean setPageSetting(User user, String url, String key, String value) { + Update update = Update.update("settings.page." + url + "." + key, value); + UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + return result.getModifiedCount() > 0L; + } + + public boolean setSitePageSetting(User user, UUID siteUuid, String url, Document settings) { + Criteria criteria = Criteria.where("_id").is(user.getUuid()).and("sites.siteUuid").is(siteUuid); + Update update = Update.update("sites.$.settings.page." + url, settings); + UpdateResult result = this.mongoTemplate.updateFirst(Query.query(criteria), update, User.class); + SiteInfo siteInfo = user.getSiteInfo(siteUuid); + if (siteInfo != null) { + siteInfo.getPageSetting(url).clear(); + siteInfo.getPageSetting(url).putAll(settings); + } + + return result.getModifiedCount() > 0L; + } + + public User findUserByUserUuid(UUID userUuid) { + return userUuid == null ? null : (User)this.findById(User.class, userUuid); + } + + public User findUserProfileByUserUuid(UUID userUuid) { + Query query = this.queryById(userUuid); + query.fields().include("email").include("profile"); + return (User)this.mongoTemplate.findOne(query, User.class); + } + + public boolean existsByEmail(String email) { + Query query = Query.query(Criteria.where("email").regex(email, "i")); + return this.mongoTemplate.exists(query, User.class); + } + + public User findUserByEmail(String email, String... fields) { + return this.findUserByEmail((UUID)null, email, fields); + } + + public User findUserByEmail(UUID siteUuid, String email, String... fields) { + Criteria criteria = Criteria.where("email").is(email); + if (siteUuid != null) { + criteria.and("sites.siteUuid").is(siteUuid); + } + + Query query = Query.query(criteria).collation(LocaleConst.COLLATION_DEFAULT); + boolean sitesIncluded = true; + if (fields != null && fields.length > 0) { + sitesIncluded = false; + Field field = query.fields(); + + for(String fieldItem : fields) { + if (fieldItem == "sites") { + sitesIncluded = true; + } + + field.include(fieldItem); + } + + if (!sitesIncluded) { + field.include("sites"); + } + } + + User user = (User)this.mongoTemplate.findOne(query, User.class); + if (user != null) { + List sites = user.getSites(); + if (!sites.isEmpty()) { + int count = sites.size(); + Iterator siteIt = sites.iterator(); + + while(siteIt.hasNext()) { + SiteInfo siteInfo = (SiteInfo)siteIt.next(); + if (!this.siteService.exists(siteInfo.getSiteUuid())) { + siteIt.remove(); + } + } + + if (sites.size() != count) { + this.save(user); + } + } + + if (user.getSiteInfo(user.getSiteUuid()) == null) { + user.setSiteUuid((UUID)null); + } + } + + return user; + } + + public User findLastestVisitor(UUID siteUuid) { + JsonObject jFilter = new JsonObject(); + jFilter.addProperty("sites.siteUuid", siteUuid.toString()); + String sortBy = "updated"; + List users = this.find(User.class, jFilter, sortBy, Direction.DESC); + return users.isEmpty() ? null : (User)users.get(0); + } + + public boolean matchPassword(User user, String password) { + if (!Strings.isNullOrEmpty(user.getPassword()) && !Strings.isNullOrEmpty(password)) { + return this.passwordEncoder.matches(password, user.getPassword()) || user.getPassword().equals(password); + } else { + return false; + } + } + + public void encodePassword(User user) { + user.encodePassword(this.passwordEncoder); + } + + public User findUser(UUID userUuid, String email) { + User user = null; + if (userUuid != null) { + user = (User)this.findById(User.class, userUuid); + } + + if (user == null && !Strings.isNullOrEmpty(email)) { + user = this.findUserByEmail(email); + } + + return user; + } + + public Page findUsers(UUID siteUuid, String filter, Integer page, Integer size, String sortBy, String direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = "asc"; + } + + JsonObject jFilter = McStringUtils.isNullOrEmpty(filter) ? new JsonObject() : McJsonUtils.toJsonElement(filter).getAsJsonObject(); + if (siteUuid != null) { + jFilter.addProperty("sites.siteUuid", siteUuid.toString()); + } + + Criteria criteria = McMongoUtils.toCriteria(jFilter); + Query query = new Query(criteria); + long total = this.mongoTemplate.count(query, User.class); + Sort sort = Sort.by(McMongoUtils.toDirection(direction), new String[]{sortBy}); + query.with(sort); + query.collation(LocaleConst.COLLATION_DEFAULT); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), User.class); + Page pageResult = new PageImpl(result, pageable, total); + + for(User user : pageResult.getContent()) { + SiteInfo siteInfo = user.getSiteInfo(siteUuid); + user.setSiteInfo(siteInfo); + user.setSites((List)null); + } + + return pageResult; + } + + public UpdateResult updateSystemRoles(String command, String role, List uuids) { + Criteria criteria = Criteria.where("_id").in(uuids); + Update update = new Update(); + if (command.equals("remove")) { + criteria.and("systemRoles").is(role); + update.pull("systemRoles", role); + } else { + criteria.and("systemRoles").nin(new Object[]{role}); + update.push("systemRoles", role); + } + + return this.mongoTemplate.updateMulti(Query.query(criteria), update, User.class); + } + + public UpdateResult updateRoles(User user, UUID siteUuid, Set roles, Boolean apiOnly) { + Criteria criteria = Criteria.where("_id").is(user.getUuid()).and("sites.siteUuid").is(siteUuid); + Update update = Update.update("sites.$.roles", roles).unset("sites.$.settings.lastPage"); + if (apiOnly != null) { + update.set("sites.$.apiOnly", apiOnly); + } + + return this.mongoTemplate.updateFirst(Query.query(criteria), update, User.class); + } + + public List findUsersBySite(UUID siteUuid) { + Query query = Query.query(Criteria.where("sites.siteUuid").is(siteUuid)); + return this.mongoTemplate.find(query, User.class); + } + + public List findSupervisors(UUID siteUuid) { + Query query = new Query(); + query.addCriteria(Criteria.where("sites").elemMatch(Criteria.where("siteUuid").is(siteUuid).and("roles").is("SUPERVISOR"))); + return this.mongoTemplate.find(query, User.class); + } + + public long countSupervisor(UUID siteUuid) { + Query query = new Query(); + query.addCriteria(Criteria.where("sites").elemMatch(Criteria.where("siteUuid").is(siteUuid).and("roles").is("SUPERVISOR"))); + return this.mongoTemplate.count(query, User.class); + } + + public Page findSupervisors(UUID siteUuid, String filter, Integer page, Integer size, String sortBy, String direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = "asc"; + } + + Query query = new Query(McMongoUtils.toCriteria(filter)); + query.addCriteria(Criteria.where("sites").elemMatch(Criteria.where("siteUuid").is(siteUuid).and("roles").is("SUPERVISOR"))); + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, User.class); + Sort sort = Sort.by(McMongoUtils.toDirection(direction), new String[]{sortBy}); + query.with(sort); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), User.class); + Page pageResult = new PageImpl(result, pageable, total); + + for(User user : pageResult.getContent()) { + SiteInfo siteInfo = user.getSiteInfo(siteUuid); + user.setSiteInfo(siteInfo); + user.setSites((List)null); + } + + return pageResult; + } + + public List findSystemAdmin() { + Criteria criteria = Criteria.where("systemRoles").is("SYSTEM_ADMIN").and("isEnabled").is(true); + Query query = new Query(criteria); + return this.mongoTemplate.find(query, User.class); + } + + public long getUserCount(UUID siteUuid) { + Query query = Query.query(Criteria.where("sites.siteUuid").is(siteUuid)); + return this.mongoTemplate.count(query, User.class); + } + + public List findUser(UUID siteUuid) { + Query query = Query.query(Criteria.where("sites.siteUuid").is(siteUuid)); + return this.mongoTemplate.find(query, User.class); + } + + public void updateLoginAttempt(User user, boolean succeed) { + Criteria criteria = Criteria.where("_id").is(user.getUuid()); + Update update; + if (succeed) { + user.resetLoginAttempt(); + update = (new Update()).unset("settings.loginAttempt"); + } else { + user.loginFailed(); + update = Update.update("settings.loginAttempt", user.getLoginAttempt()); + } + + this.mongoTemplate.updateFirst(Query.query(criteria), update, user.getClass()); + } + + public void deleteUser(UUID userUuid) { + if (userUuid != null) { + this.deleteTokenByUser(userUuid); + this.logService.clearAllLogsFor(userUuid); + this.deviceService.removeOwner(userUuid); + this.deleteById(User.class, userUuid); + String userFilePath = Joiner.on('/').join(this.settingsService.getFilesRootPath(), "user", new Object[]{userUuid}); + (new McFile(userFilePath)).delete(); + } + } + + public void delete(User user) { + if (user != null && user.getUuid() != null) { + this.deleteUser(user.getUuid()); + } + } + + public void deleteUserByEmail(String email) { + User user = this.findUserByEmail(email); + if (user != null) { + this.deleteUser(user.getUuid()); + } + + } + + public User update(User user) { + User existingUser = (User)this.findById(User.class, user.getUuid()); + return existingUser == null ? null : (User)this.saveDocument(user); + } + + public UpdateResult updateProfile(User user) { + Update update = Update.update("profile", user.getProfile()); + return this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); + } + + public UserToken save(UserToken token) { + if (token.getTokenType() != 'D') { + this.deleteTokenByType(token); + } else { + this.deleteDeviceAccessToken(token); + } + + return (UserToken)this.saveDocument(token); + } + + public UserToken renew(UserToken token) { + this.delete(token); + token.renew(); + return (UserToken)this.saveDocument(token); + } + + public UserToken findToken(User user, Character tokenType) { + if (user != null && user.getUuid() != null && tokenType != null) { + Query query = Query.query(Criteria.where("userUuid").is(user.getUuid()).and("tokenType").is(tokenType)); + return (UserToken)this.mongoTemplate.findOne(query, UserToken.class); + } else { + return null; + } + } + + public UserToken findToken(UUID tokenUuid) { + UserToken token = tokenUuid == null ? null : (UserToken)this.findById(UserToken.class, tokenUuid); + if (token != null && token.isExpired()) { + this.delete(token); + token = null; + } + + return token; + } + + public UserToken findToken(String tokenBase64) { + UUID tokenUuid = McUuidUtils.toUuidFromBase64(tokenBase64); + return tokenUuid == null ? null : (UserToken)this.findById(UserToken.class, tokenUuid); + } + + public void delete(UserToken token) { + if (token != null) { + this.deleteById(UserToken.class, token.getTokenUuid()); + } + + } + + public void deleteTokenByType(UserToken token) { + this.deleteToken(token.getUserUuid(), token.getTokenType()); + } + + public void deleteTokenByUser(UUID userUuid) { + Query query = Query.query(Criteria.where("userUuid").is(userUuid)); + this.mongoTemplate.remove(query, UserToken.class); + } + + public void deleteLoginToken(User user) { + this.deleteToken(user, 'L'); + } + + public void deleteToken(User user, char tokenType) { + this.deleteToken(user.getUuid(), tokenType); + } + + public void deleteToken(UUID userUuid, char tokenType) { + Query query = Query.query(Criteria.where("userUuid").is(userUuid).and("tokenType").is(tokenType)); + this.mongoTemplate.remove(query, UserToken.class); + } + + public void deleteDeviceAccessToken(UserToken token) { + Query query = Query.query(Criteria.where("reference.deviceUuid").is(token.getDeviceUuid()).and("tokenType").is(token.getTokenType())); + this.mongoTemplate.remove(query, UserToken.class); + } + + public Authentication authorizeLogin(User user) { + UserToken token = new UserToken(user, 'L', 604800000L); + token.encryptToken(); + Authentication authentication = new UsernamePasswordAuthenticationToken(new UserPrincipal(user), token, user.getAuthorities()); + SecurityContextHolder.getContext().setAuthentication(authentication); + this.save(token); + if (user.getSiteUuid() != null) { + Site site = this.siteService.findByUuid(user.getSiteUuid()); + if (site != null) { + user.setSite(site); + } + } + + return authentication; + } + + public Authentication updateAuthorizedUser(User user) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + UserToken token = this.findToken(user, 'L'); + if (token == null) { + return this.authorizeLogin(user); + } else { + authentication = new UsernamePasswordAuthenticationToken(new UserPrincipal(user), token, user.getAuthorities()); + SecurityContextHolder.getContext().setAuthentication(authentication); + return authentication; + } + } + + public Authentication authorizeLogin(UUID tokenUuid) { + UserToken token = this.findToken(tokenUuid); + if (token == null) { + return null; + } else if (token.isExpired()) { + this.delete(token); + return null; + } else { + this.delete(token); + User user = this.findUserByUserUuid(token.getUserUuid()); + return this.authorizeLogin(user); + } + } + + public User authorizedUser(Authentication authentication, String accessToken) { + User user = UserPrincipal.getUser(authentication); + if (user == null && !Strings.isNullOrEmpty(accessToken) && accessToken.startsWith("Bearer")) { + try { + UUID tokenUuid = McUuidUtils.toUuidFromBase64(accessToken.substring(7)); + UserToken token = this.findToken(tokenUuid); + if (token != null) { + if (token.isExpired()) { + this.delete(token); + } else { + user = this.findUserByUserUuid(token.getUserUuid()); + } + } + } catch (Exception var6) { + } + } + + return user; + } + + public UserGroup save(UserGroup group) { + if (group.getUuid() == null) { + group.init(); + } + + return (UserGroup)this.saveDocument(group); + } + + public UserGroup findUserGroup(UUID groupUuid) { + return groupUuid == null ? null : (UserGroup)this.findById(UserGroup.class, groupUuid); + } + + public UserGroup findUserGroup(UUID siteUuid, String path) { + if (McStringUtils.isNullOrEmpty(path)) { + return null; + } else { + String[] elements = path.split(Pattern.quote("/")); + UserGroup parentGroup = null; + + for(String name : elements) { + UserGroup group = this.findUserGroup(siteUuid, parentGroup, name); + if (group == null) { + parentGroup = this.save(new UserGroup(siteUuid, parentGroup, name)); + } else { + parentGroup = group; + } + } + + return parentGroup; + } + } + + public List findUserGroupByName(UUID siteUuid, String name) { + if (siteUuid == null) { + return null; + } else { + String sortBy = "profile.hardware.serial_number"; + JsonObject jFilter = this.getProfileFilter("name", name); + jFilter.addProperty("siteUuid", siteUuid.toString()); + List groups = this.find(UserGroup.class, jFilter, "profile.hardware.serial_number", Direction.ASC); + return groups; + } + } + + private UserGroup findUserGroup(UUID siteUuid, UserGroup parent, String childName) { + if (siteUuid == null) { + return null; + } else { + Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("profile.name").is(childName); + if (parent == null) { + criteria.and("parentUuid").isNull(); + } else { + criteria.and("parentUuid").is(parent.getUuid()); + } + + return (UserGroup)this.mongoTemplate.findOne(Query.query(criteria), UserGroup.class); + } + } + + public List findAllUserGroups(UUID siteUuid) { + Sort sort = Sort.by(new String[]{"parentUuid"}).and(Sort.by(new String[]{"order"})).and(Sort.by(new String[]{"profile.name"})); + Query queryBySite = Query.query(Criteria.where("siteUuid").is(siteUuid)); + queryBySite.with(sort); + List groups = this.mongoTemplate.find(queryBySite, UserGroup.class); + + for(UserGroup group : groups) { + UUID groupUuid = group.getUuid(); + if (groupUuid != null) { + Query queryByGroup = Query.query(Criteria.where("sites.groupUuid").is(groupUuid)); + Long numbers = this.mongoTemplate.count(queryByGroup, User.class); + group.setUserNumbers(numbers); + } + } + + return groups; + } + + public Page findUserGroup(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "profile.name"; + direction = Direction.ASC; + } + + List result = this.find(UserGroup.class, filter, sortBy, direction); + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public void delete(UserGroup group) { + if (group != null && group.getUuid() != null) { + Query queryByParent = Query.query(Criteria.where("parentUuid").is(group.getUuid())); + + for(UserGroup childGroup : this.mongoTemplate.find(queryByParent, UserGroup.class)) { + this.delete(childGroup); + } + + this.deleteById(UserGroup.class, group.getUuid()); + Query query = Query.query(Criteria.where("sites.groupUuid").is(group.getUuid())); + Update update = (new Update()).unset("sites.$.groupUuid"); + this.mongoTemplate.updateMulti(query, update, User.class); + } + } + + public DeleteResult deleteUserGroupBySiteUuid(UUID siteUuid) { + Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); + return this.mongoTemplate.remove(query, UserGroup.class); + } + + @Async + public void clearExpiredTokens() { + this.mongoTemplate.remove(Query.query(Criteria.where("expired").lt(new Date())), UserToken.class); + } + + @Async + public void updateUserNameIfNotExists() { + Query query = Query.query(Criteria.where("profile.name").exists(false)); + + for(User user : this.mongoTemplate.find(query, User.class)) { + String email = user.getEmail(); + if (McEmailUtils.isValid(email)) { + String name = user.getEmail().substring(0, user.getEmail().indexOf("@")); + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(user.getUuid())), Update.update("profile.name", name), User.class); + } else { + this.mongoTemplate.remove(user); + } + } + + } +} diff --git a/src/main/java/com/midm/service/store/KeyStoreService.java b/src/main/java/com/midm/service/store/KeyStoreService.java new file mode 100644 index 0000000..a0733de --- /dev/null +++ b/src/main/java/com/midm/service/store/KeyStoreService.java @@ -0,0 +1,56 @@ +package com.midm.service.store; + +import com.google.common.base.Joiner; +import com.google.gson.JsonObject; +import com.midm.model.store.KeyStore; +import com.midm.service.BaseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McStringUtils; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.stereotype.Service; + +@Service +public class KeyStoreService extends BaseService { + @Autowired + private SettingsService settingsService; + + public Page findKeys(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "id"; + direction = Direction.ASC; + } + + List result = this.find(KeyStore.class, filter, sortBy, direction); + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public KeyStore save(KeyStore key) { + return (KeyStore)this.saveDocument(key); + } + + public KeyStore find(String id) { + return (KeyStore)this.findById(KeyStore.class, id); + } + + public void delete(String id) { + this.deleteById(KeyStore.class, id); + String targetFilePath = this.getFilePath(id); + (new McFile(targetFilePath)).delete(); + } + + public List findAll() { + return this.findAll(KeyStore.class); + } + + public String getFilePath(String id) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "keyStore", new Object[]{id}); + } +} diff --git a/src/main/java/com/midm/service/store/StoreAppService.java b/src/main/java/com/midm/service/store/StoreAppService.java new file mode 100644 index 0000000..a88cc3f --- /dev/null +++ b/src/main/java/com/midm/service/store/StoreAppService.java @@ -0,0 +1,425 @@ +package com.midm.service.store; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.device.AppInfo; +import com.midm.model.org.User; +import com.midm.model.store.AppReleaseNote; +import com.midm.model.store.KeyStore; +import com.midm.model.store.StoreApp; +import com.midm.model.store.StoreAppFile; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.file.FileService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McApkFile; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McStringUtils; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.apache.commons.io.IOUtils; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class StoreAppService extends BaseService { + @Autowired + private SettingsService settingsService; + @Autowired + @Lazy + @Qualifier("fileService") + private FileService fileService; + @Autowired + private CloudStorageService cloudStorageService; + + public StoreApp save(StoreApp app, String oldPackageName) { + if (oldPackageName != null) { + this.deleteById(StoreApp.class, oldPackageName); + } + + StoreApp existingApp = this.find(app.getPackageName()); + if (existingApp == null) { + app.init(); + } + + app.setSdkVersions((Set)null); + app.setLastUpdated(new Date()); + return (StoreApp)this.saveDocument(app); + } + + public List findAll() { + return this.findAll(StoreApp.class); + } + + public List findAll(int minSdkVersion) { + List pipeline = Arrays.asList(new Document("$match", new Document("appInfo.minSdkVersion", new Document("$lte", minSdkVersion))), new Document("$sort", new Document("appInfo.versionCode", 1)), new Document("$group", (new Document("_id", "$appInfo.packageName")).append("appInfo", new Document("$last", "$appInfo"))), new Document("$project", (new Document("_id", 0)).append("packageName", "$appInfo.packageName").append("label", "$appInfo.label").append("minSdkVersion", "$appInfo.minSdkVersion").append("versionCode", "$appInfo.versionCode").append("versionName", "$appInfo.versionName"))); + List apps = this.mongoTemplate.aggregate(Aggregations.from(pipeline), StoreAppFile.class, AppInfo.class).getMappedResults(); + return apps; + } + + public List getSdkVersions(String packageName) { + Query query = Query.query(Criteria.where("_id.packageName").is(packageName)); + return this.mongoTemplate.findDistinct(query, "minSdkVersion", AppReleaseNote.class, Integer.class); + } + + public StoreApp find(String packageName) { + StoreApp app = (StoreApp)this.findById(StoreApp.class, packageName); + if (app != null) { + app.setSdkVersions(this.getSdkVersions(packageName)); + } + + return app; + } + + public StoreAppFile findAppFile(UUID fileUuid) { + return (StoreAppFile)this.findById(StoreAppFile.class, fileUuid); + } + + public StoreAppFile findLatestAppFile(String packageName, int versionCode, int sdkVersion, String certMd5) { + Criteria criteria = Criteria.where("appInfo.packageName").is(packageName); + if (sdkVersion > 0) { + criteria = criteria.and("appInfo.minSdkVersion").lte(sdkVersion); + } + + if (versionCode > 0) { + criteria = criteria.and("appInfo.versionCode").gt(versionCode); + } + + if (!Strings.isNullOrEmpty(certMd5)) { + criteria = criteria.and("appInfo.certMd5").is(certMd5); + } + + Sort sort = Sort.by(Direction.DESC, new String[]{"appInfo.minSdkVersion"}).and(Sort.by(Direction.DESC, new String[]{"appInfo.versionCode"})); + Query query = Query.query(criteria).with(sort); + return (StoreAppFile)this.mongoTemplate.findOne(query, StoreAppFile.class); + } + + public StoreAppFile findAppFile(String packageName, long versionCode, String certMd5) { + Criteria criteria = Criteria.where("appInfo.packageName").is(packageName).and("appInfo.certMd5").is(certMd5); + Query query = Query.query(criteria); + if (versionCode > 0L) { + criteria.and("appInfo.versionCode").is(versionCode); + } else { + query.with(Sort.by(Direction.DESC, new String[]{"appInfo.versionCode"})); + } + + return (StoreAppFile)this.mongoTemplate.findOne(query, StoreAppFile.class); + } + + public StoreAppFile findAppFile(StoreAppFile file) { + return this.findAppFile(file.getPackageName(), file.getVersionCode(), file.getCertMd5()); + } + + public void deleteAppFile(UUID fileUuid) { + StoreAppFile appFile = this.findAppFile(fileUuid); + String targetFilePath = this.getStoreAppPath(appFile.getPackageName(), appFile.getVersionCode(), fileUuid); + (new McFile(targetFilePath)).delete(); + this.cloudStorageService.delete("store", "app", appFile.getPackageName(), appFile.getVersionCode(), fileUuid); + this.deleteById(StoreAppFile.class, fileUuid); + } + + public void delete(String packageName, int versionCode, boolean filesOnly) { + if (versionCode <= 0) { + this.deleteById(StoreApp.class, packageName); + } + + Criteria criteria = Criteria.where("appInfo.packageName").is(packageName); + if (versionCode >= 0) { + criteria.and("appInfo.versionCode").is(versionCode); + } + + this.mongoTemplate.remove(Query.query(criteria), StoreAppFile.class); + String targetFilePath = this.getStoreFilePath(packageName, "app"); + if (versionCode >= 0) { + targetFilePath = targetFilePath + "/" + versionCode; + } + + (new McFile(targetFilePath)).delete(); + if (versionCode < 0) { + this.cloudStorageService.delete("store", "app", packageName); + } else { + this.cloudStorageService.delete("store", "app", packageName, versionCode); + } + + if (!filesOnly) { + criteria = Criteria.where("_id.packageName").is(packageName); + if (versionCode >= 0) { + criteria.and("_id.versionCode").is(versionCode); + } + + this.mongoTemplate.remove(Query.query(criteria), AppReleaseNote.class); + } + + } + + public List findApps(String packageName) { + return this.findAppFiles(packageName, -1); + } + + public List findAppFiles(String packageName, int versionCode) { + Criteria criteria = Criteria.where("appInfo.packageName").is(packageName); + if (versionCode > 0) { + criteria = criteria.and("appInfo.versionCode").is(versionCode); + } + + Sort sort = Sort.by(Direction.DESC, new String[]{"appInfo.versionCode"}); + List storeAppFiles = this.mongoTemplate.find(Query.query(criteria).with(sort), StoreAppFile.class); + return storeAppFiles; + } + + public Page findApps(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "title.en-US"; + direction = Direction.ASC; + } + + Page pageResult = this.findByPage(StoreApp.class, filter, sortBy, direction, page, size); + pageResult.forEach((app) -> { + StoreAppFile appFile = this.findLatestAppFile(app.getPackageName(), -1, -1, (String)null); + if (appFile != null) { + app.setAppInfo(appFile.getAppInfo()); + app.setLastUpdated(appFile.getLastUpdated()); + } + + }); + return pageResult; + } + + public void save(StoreAppFile app) { + this.saveDocument(app); + } + + public String getTempFilePath(String fileType, UUID fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"temp", fileType, fileUuid}); + } + + public String getStoreFilePath(String packageName, String fileType) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{fileType, packageName}); + } + + public String getStoreAppPath(String packageName, long versionCode, UUID fileUuid) { + return Joiner.on('/').join(this.getStoreFilePath(packageName, "app"), versionCode, new Object[]{fileUuid}); + } + + public String getStoreIconPath(String packageName) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"app", packageName, "icon.png"}); + } + + public AppReleaseNote addReleaseNote(String packageName, int versionCode, String versionName, int minSdkVersion) { + AppReleaseNote releaseNote = new AppReleaseNote(packageName, versionCode, versionName, minSdkVersion); + return this.save(releaseNote); + } + + public void addReleaseNote(StoreAppFile appFile) { + AppReleaseNote releaseNote = new AppReleaseNote(appFile); + this.save(releaseNote); + } + + public AppReleaseNote findReleaseNote(String packageName, int versionCode) { + Criteria criteria = Criteria.where("_id.packageName").is(packageName).and("_id.versionCode").is(versionCode); + AppReleaseNote releaseNote = (AppReleaseNote)this.mongoTemplate.findOne(Query.query(criteria), AppReleaseNote.class); + return releaseNote; + } + + public List findReleaseNote(String packageName, Boolean isFormal) { + return this.findReleaseNotes(packageName, -1, isFormal); + } + + public List findReleaseNotes(String packageName, int sdkVersion, Boolean isFormal) { + Criteria criteria = Criteria.where("_id.packageName").is(packageName); + if (sdkVersion > 0) { + criteria.and("minSdkVersion").is(sdkVersion); + } + + if (isFormal != null) { + criteria.and("isFormal").is(isFormal); + } + + Sort sort = Sort.by(Direction.DESC, new String[]{"releasedAt"}); + List releaseNotes = this.mongoTemplate.find(Query.query(criteria).with(sort), AppReleaseNote.class); + return releaseNotes; + } + + public boolean releaseNoteExists(String packageName, int versionCode) { + Criteria criteria = Criteria.where("_id.packageName").is(packageName).and("_id.versionCode").is(versionCode); + return this.mongoTemplate.exists(Query.query(criteria), AppReleaseNote.class); + } + + public Page findReleaseNotes(String packageName, int sdkVersion, String certMd5, int page, int size) { + Query query = new Query(); + query.addCriteria(Criteria.where("_id.packageName").is(packageName)); + if (sdkVersion > 0) { + query.addCriteria(Criteria.where("minSdkVersion").is(sdkVersion)); + } + + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, AppReleaseNote.class); + if (total <= 0L) { + return new PageImpl(new ArrayList(), PageRequest.of(0, 10), total); + } else { + if (page < 0 || size == 0) { + page = 0; + size = (int)total; + } + + Pageable pageable = PageRequest.of(0, (int)total); + List matchConditions = new ArrayList(); + matchConditions.add(new DbObject("_id.packageName", packageName)); + List pipelineMatchOperation = new ArrayList(Arrays.asList(new DbObject("$eq", Arrays.asList("$appInfo.packageName", "$$packageName")), new DbObject("$eq", Arrays.asList("$appInfo.versionCode", "$$versionCode")))); + if (sdkVersion > 0) { + matchConditions.add(new DbObject("minSdkVersion", sdkVersion)); + pipelineMatchOperation.add(new DbObject("$eq", Arrays.asList("$appInfo.minSdkVersion", sdkVersion))); + } + + if (!Strings.isNullOrEmpty(certMd5)) { + pipelineMatchOperation.add(new DbObject("$eq", Arrays.asList("$appInfo.certMd5", certMd5))); + } + + List pipeline = Arrays.asList(new DbObject("$match", new DbObject("$and", matchConditions)), new DbObject("$lookup", (new DbObject()).append("from", "storeAppFile").append("let", (new DbObject("packageName", "$_id.packageName")).append("versionCode", "$_id.versionCode")).append("pipeline", Arrays.asList(new DbObject("$match", new DbObject("$expr", new DbObject("$and", pipelineMatchOperation))))).append("as", "files")), new DbObject("$sort", new DbObject("_id.versionCode", -1)), new DbObject("$skip", page * size), new DbObject("$limit", size)); + List notes = this.mongoTemplate.aggregate(Aggregations.from(pipeline), AppReleaseNote.class, AppReleaseNote.class).getMappedResults(); + return new PageImpl(notes, pageable, total); + } + } + + public AppReleaseNote save(AppReleaseNote releaseNote) { + releaseNote.setFiles((List)null); + return (AppReleaseNote)this.saveDocument(releaseNote); + } + + public AppReleaseNote updateNote(String packageName, int versionCode, String versionName, int minSdkVersion, String[] notes, String[] noteNewFunctions, Date releasedAt) { + AppReleaseNote releaseNote = (AppReleaseNote)this.findById(AppReleaseNote.class, new AppReleaseNote.NoteId(packageName, versionCode)); + if (releaseNote == null) { + releaseNote = new AppReleaseNote(packageName, versionCode, versionName, minSdkVersion); + return this.save(releaseNote); + } else { + List newNotes = new ArrayList(); + if (notes != null) { + for(String note : notes) { + try { + newNotes.add(URLDecoder.decode(note, StandardCharsets.UTF_8.name())); + } catch (UnsupportedEncodingException var17) { + } + } + } + + List newNoteNewFunctions = new ArrayList(); + if (noteNewFunctions != null) { + for(String note : noteNewFunctions) { + try { + newNoteNewFunctions.add(URLDecoder.decode(note, StandardCharsets.UTF_8.name())); + } catch (UnsupportedEncodingException var16) { + } + } + } + + releaseNote.setNotes((String[])newNotes.toArray(new String[newNotes.size()])); + releaseNote.setNoteNewFunctions((String[])newNoteNewFunctions.toArray(new String[newNoteNewFunctions.size()])); + if (releasedAt != null) { + releaseNote.setReleasedAt(releasedAt); + } + + return this.save(releaseNote); + } + } + + public AppReleaseNote updateNoteIsFormal(String packageName, int versionCode, boolean isFormal) { + AppReleaseNote releaseNote = (AppReleaseNote)this.findById(AppReleaseNote.class, new AppReleaseNote.NoteId(packageName, versionCode)); + if (releaseNote != null) { + releaseNote.setIsFormal(isFormal); + releaseNote = this.save(releaseNote); + } + + return releaseNote; + } + + public void sign(User user, McFile file, String originalFileName) { + if (file.exists()) { + McApkFile apkFile = null; + String packageName = null; + long versionCode = 0L; + + try { + apkFile = new McApkFile(file); + packageName = apkFile.getApkMeta().getPackageName(); + versionCode = apkFile.getApkMeta().getVersionCode(); + apkFile.close(); + } catch (IOException var16) { + return; + } + + if (!Strings.isNullOrEmpty(packageName)) { + for(KeyStore keyStore : this.findAll(KeyStore.class)) { + String keyPath = Joiner.on('/').join(this.settingsService.getFilesRootPath(), "keyStore", new Object[]{keyStore.getId()}); + if ((new McFile(keyPath)).exists()) { + StoreAppFile curAppFile = this.findAppFile(packageName, versionCode, keyStore.getCertMd5()); + UUID fileUuid = curAppFile != null ? curAppFile.getFileUuid() : UUID.randomUUID(); + String outputApkPath = this.getStoreAppPath(packageName, versionCode, fileUuid); + McFile outputFile = new McFile(outputApkPath); + if (!outputFile.getParentFile().exists()) { + outputFile.getParentFile().mkdirs(); + } + + this.sign(file.getPath(), outputApkPath, keyPath, keyStore.getAlias(), keyStore.getKeyPassword(), keyStore.getStorePassword(), user, fileUuid, packageName, keyStore.getId()); + } + } + + } + } + } + + public String sign(String inputApkPath, String outputApkPath, String keyStoreFilePath, String keyStoreAlias, String keyPassword, String storePassword, User user, UUID fileUuid, String packageName, String keyID) { + McFile apkSigner = this.fileService.getResourceFile("apksigner/apksigner.jar", false); + + try { + ProcessBuilder builder = (new ProcessBuilder(new String[0])).command("java", "-jar", apkSigner.getPath(), "sign", "--ks", keyStoreFilePath, "--ks-key-alias", keyStoreAlias, "--key-pass", "pass:" + keyPassword, "--ks-pass", "pass:" + storePassword, "--out", outputApkPath, inputApkPath); + Process process = builder.start(); + int code = process.waitFor(); + if (code == 0) { + McFile apkFile = new McFile(outputApkPath); + StoreAppFile appFile = new StoreAppFile(user, fileUuid, apkFile, false); + String versionName = appFile.getVersionName(); + String fileName = appFile.getLabel().replaceAll("\\s", "") + "-" + versionName + "-" + keyID + ".apk"; + appFile.setFileName(fileName); + this.save(appFile); + (new McFile(apkFile.getPath() + ".idsig")).delete(); + if (this.cloudStorageService.hasCloudStorage()) { + this.cloudStorageService.upload(apkFile, fileName, apkFile.getContentType(), "store", "app", appFile.getPackageName(), appFile.getVersionCode(), fileUuid); + } + + return "signed"; + } else { + String error = IOUtils.toString(process.getErrorStream(), "UTF-8"); + return error; + } + } catch (IOException e) { + e.printStackTrace(); + return e.getMessage(); + } catch (InterruptedException e) { + e.printStackTrace(); + return e.getMessage(); + } + } +} diff --git a/src/main/java/com/midm/service/store/StoreOtaService.java b/src/main/java/com/midm/service/store/StoreOtaService.java new file mode 100644 index 0000000..b1cae85 --- /dev/null +++ b/src/main/java/com/midm/service/store/StoreOtaService.java @@ -0,0 +1,180 @@ +package com.midm.service.store; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.store.StoreOta; +import com.midm.model.store.StoreOtaFile; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McStringUtils; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class StoreOtaService extends BaseService { + @Autowired + private SettingsService settingsService; + @Autowired + private CloudStorageService cloudStorageService; + + public StoreOta save(StoreOta ota) { + return (StoreOta)this.saveDocument(ota); + } + + public Page findOtas(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "productId"; + direction = Direction.ASC; + } + + List result = this.find(StoreOta.class, filter, sortBy, direction); + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public List findAll() { + return this.findAll(StoreOta.class); + } + + public List findOtaFiles(String productId) { + Query query = Query.query(Criteria.where("otaInfo.productId").is(productId)); + return this.mongoTemplate.find(query, StoreOtaFile.class); + } + + public Page findOtaFiles(String productId, int page, int size) { + Query query = new Query(); + query.addCriteria(Criteria.where("otaInfo.productId").is(productId)); + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, StoreOtaFile.class); + if (total <= 0L) { + return null; + } else { + if (page < 0 || size == 0) { + page = 0; + size = (int)total; + } + + Pageable pageable = PageRequest.of(0, (int)total); + List matchConditions = new ArrayList(); + matchConditions.add(new Document("otaInfo.productId", productId)); + List pipeline = Arrays.asList(new Document("$match", new Document("$and", matchConditions)), new Document("$sort", new Document("otaInfo.buildDate", -1)), new Document("$skip", page * size), new Document("$limit", size)); + List storeOtaFiles = this.mongoTemplate.aggregate(Aggregations.from(pipeline), StoreOtaFile.class, StoreOtaFile.class).getMappedResults(); + return new PageImpl(storeOtaFiles, pageable, total); + } + } + + public StoreOta find(String productId) { + Criteria criteria = (new Criteria()).orOperator(new Criteria[]{Criteria.where("_id").is(productId), Criteria.where("deviceId").is(productId)}); + return (StoreOta)this.mongoTemplate.findOne(Query.query(criteria), StoreOta.class); + } + + public StoreOtaFile findOtaFile(UUID fileUuid) { + return (StoreOtaFile)this.findById(StoreOtaFile.class, fileUuid); + } + + public StoreOtaFile find(String productId, long buildDate) { + Criteria criteria = Criteria.where("otaInfo.productId").is(productId); + if (buildDate > 0L) { + criteria.and("otaInfo.buildDate").is(buildDate); + } + + Query query = Query.query(criteria); + StoreOtaFile otaFile = (StoreOtaFile)this.mongoTemplate.findOne(query, StoreOtaFile.class); + return otaFile; + } + + public StoreOtaFile findLatest(String productId, String skuId, long buildDate) { + List andSet = new ArrayList(); + andSet.add((new Criteria()).orOperator(new Criteria[]{Criteria.where("otaInfo.productId").is(productId), Criteria.where("otaInfo.deviceId").is(productId)})); + if (!Strings.isNullOrEmpty(skuId)) { + andSet.add((new Criteria()).orOperator(new Criteria[]{Criteria.where("otaInfo.displayId").regex(String.format(".*%s.*", skuId))})); + } + + if (buildDate > 0L) { + andSet.add(Criteria.where("otaInfo.buildDate").gt(buildDate)); + } + + Criteria criteria = (new Criteria()).andOperator((Criteria[])andSet.toArray(new Criteria[andSet.size()])); + Sort sort = Sort.by(Direction.DESC, new String[]{"otaInfo.buildDate"}); + Query query = Query.query(criteria).with(sort); + StoreOtaFile otaFile = (StoreOtaFile)this.mongoTemplate.findOne(query, StoreOtaFile.class); + return otaFile; + } + + public StoreOtaFile save(StoreOtaFile ota) { + return (StoreOtaFile)this.saveDocument(ota); + } + + public void remove(String productId) { + this.deleteById(StoreOta.class, productId); + } + + public String getStoreFilePath(String productId) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"ota", productId}); + } + + public String getStoreOtaFilePath(String productId, UUID fileUuid) { + return Joiner.on('/').join(this.getStoreFilePath(productId), fileUuid, new Object[0]); + } + + public String getTempFilePath(UUID fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"temp", "ota", fileUuid}); + } + + public void deleteSingleFile(UUID fileUuid, String productId) { + Criteria criteria = Criteria.where("fileUuid").is(fileUuid); + this.mongoTemplate.remove(Query.query(criteria), StoreOtaFile.class); + String targetFilePath = this.getStoreOtaFilePath(productId, fileUuid); + (new McFile(targetFilePath)).delete(); + this.cloudStorageService.delete("store", "ota", productId, fileUuid); + } + + public void delete(String productId) { + this.deleteById(StoreOta.class, productId); + Criteria criteria = Criteria.where("otaInfo.productId").is(productId); + this.mongoTemplate.remove(Query.query(criteria), StoreOtaFile.class); + String targetFilePath = this.getStoreFilePath(productId); + (new McFile(targetFilePath)).delete(); + this.cloudStorageService.delete("store", "ota", productId); + } + + public StoreOtaFile updateNote(UUID fileUuid, String[] notes) { + StoreOtaFile otaFile = this.findOtaFile(fileUuid); + if (otaFile == null) { + return null; + } else { + List newNotes = new ArrayList(); + + for(String note : notes) { + try { + newNotes.add(URLDecoder.decode(note, StandardCharsets.UTF_8.name())); + } catch (UnsupportedEncodingException var10) { + } + } + + otaFile.setNotes((String[])newNotes.toArray(new String[newNotes.size()])); + return this.save(otaFile); + } + } +} diff --git a/src/main/java/com/midm/service/store/StoreOtherService.java b/src/main/java/com/midm/service/store/StoreOtherService.java new file mode 100644 index 0000000..fb908b3 --- /dev/null +++ b/src/main/java/com/midm/service/store/StoreOtherService.java @@ -0,0 +1,127 @@ +package com.midm.service.store; + +import com.google.common.base.Joiner; +import com.google.gson.JsonObject; +import com.midm.model.store.StoreOtherFile; +import com.midm.service.BaseService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McStringUtils; +import java.util.List; +import java.util.UUID; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class StoreOtherService extends BaseService { + @Autowired + private SettingsService settingsService; + @Autowired + private CloudStorageService cloudStorageService; + + public void deleteFile(UUID fileUuid) { + this.deleteById(StoreOtherFile.class, fileUuid); + (new McFile(this.getStoreFilePath("other", fileUuid))).delete(); + this.cloudStorageService.delete("store", "other", fileUuid); + } + + public Page find(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "name"; + direction = Direction.ASC; + } + + List result = this.find(StoreOtherFile.class, filter, sortBy, direction); + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public void save(StoreOtherFile file) { + this.saveDocument(file); + } + + public StoreOtherFile findByUuid(UUID fileUuid) { + return (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(fileUuid)), StoreOtherFile.class); + } + + public StoreOtherFile findByName(String name) { + return (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("fileInfo.fileName").is(name)), StoreOtherFile.class); + } + + public StoreOtherFile findByAlias(String alias) { + return (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("alias").is(alias)), StoreOtherFile.class); + } + + public String getNewAlias(McFile file) { + String alias = file.getNameWithoutExtension(); + if (!this.existsByAlias(alias)) { + return alias; + } else { + alias = file.getName(); + if (!this.existsByAlias(alias)) { + return alias; + } else { + int i = 0; + + do { + alias = String.format("%s_", file.getNameWithoutExtension(), i++); + } while(this.existsByAlias(alias)); + + return alias; + } + } + } + + public boolean existsByAlias(String alias) { + return this.mongoTemplate.exists(Query.query(Criteria.where("alias").is(alias)), StoreOtherFile.class); + } + + public StoreOtherFile findByUuidOrNameOrAlias(String uuriOrNameOrAlias) { + StoreOtherFile file = null; + + try { + UUID uuid = UUID.fromString(uuriOrNameOrAlias); + file = (StoreOtherFile)this.findById(StoreOtherFile.class, uuid); + } catch (Exception var4) { + file = (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("alias").is(uuriOrNameOrAlias)), StoreOtherFile.class); + if (file == null) { + file = (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("fileInfo.fileName").is(uuriOrNameOrAlias)), StoreOtherFile.class); + } + } + + return file; + } + + public boolean fileNameExists(UUID fileUuid, String name, UUID siteUuid) { + Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); + Query query = Query.query(criteria); + StoreOtherFile file = (StoreOtherFile)this.mongoTemplate.findOne(query, StoreOtherFile.class); + return file != null && !file.getFileUuid().equals(fileUuid); + } + + public void removeSameFile(UUID fileUuid, String name, UUID siteUuid) { + Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); + Query query = Query.query(criteria); + this.mongoTemplate.remove(query, StoreOtherFile.class); + } + + public String getStoreFilePath(String fileType, UUID fileUuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{fileType, fileUuid}); + } + + public String getStoreFilePath(String packageName, String fileType) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{fileType, packageName}); + } + + public String getStoreAppPath(String packageName, long versionCode, UUID fileUuid) { + return Joiner.on('/').join(this.getStoreFilePath(packageName, "app"), versionCode, new Object[]{fileUuid}); + } +} diff --git a/src/main/java/com/midm/service/store/StoreWebAppService.java b/src/main/java/com/midm/service/store/StoreWebAppService.java new file mode 100644 index 0000000..7ac4502 --- /dev/null +++ b/src/main/java/com/midm/service/store/StoreWebAppService.java @@ -0,0 +1,197 @@ +package com.midm.service.store; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.midm.constant.LocaleConst; +import com.midm.model.store.StoreWebApp; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.io.McFile; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationResults; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +@Service +public class StoreWebAppService extends BaseService { + @Autowired + private SettingsService settingsService; + @Autowired + private CloudStorageService cloudStorageService; + + public void save(StoreWebApp appFile) { + this.mongoTemplate.save(appFile); + } + + public boolean exists(UUID fileUuid) { + Query query = Query.query(Criteria.where("_id").is(fileUuid)); + return this.mongoTemplate.exists(query, StoreWebApp.class); + } + + public boolean updateNote(UUID appFileUuid, List notes, List notesNewFunction) { + List newNotes = new ArrayList(); + if (notes != null) { + for(String note : notes) { + try { + newNotes.add(URLDecoder.decode(note, StandardCharsets.UTF_8.name())); + } catch (UnsupportedEncodingException var10) { + } + } + } + + List newNotesNewFunction = new ArrayList(); + if (notesNewFunction != null) { + for(String note : notesNewFunction) { + try { + newNotesNewFunction.add(URLDecoder.decode(note, StandardCharsets.UTF_8.name())); + } catch (UnsupportedEncodingException var9) { + } + } + } + + Query query = Query.query(Criteria.where("_id").is(appFileUuid)); + Update update = new Update(); + if (newNotes.isEmpty()) { + update.unset("releaseNote"); + } else { + update.set("releaseNote", newNotes); + } + + if (newNotesNewFunction.isEmpty()) { + update.unset("releaseNoteNewFunction"); + } else { + update.set("releaseNoteNewFunction", newNotesNewFunction); + } + + return this.mongoTemplate.updateFirst(query, update, StoreWebApp.class).getModifiedCount() > 0L; + } + + public boolean setToFormal(UUID appFileUuid, boolean isFormal) { + Query query = Query.query(Criteria.where("_id").is(appFileUuid)); + Update update = new Update(); + if (isFormal) { + update.set("isFormal", isFormal); + } else { + update.unset("isFormal"); + } + + return this.mongoTemplate.updateFirst(query, update, StoreWebApp.class).getModifiedCount() > 0L; + } + + public List getArtifacts() { + List pipeline = new ArrayList(Arrays.asList(new Document("$group", (new Document("_id", "$appInfo.artifactId")).append("name", new Document("$first", "$name"))))); + List artifacts = new ArrayList(); + Aggregation aggregation = Aggregations.from(pipeline); + AggregationResults results = this.mongoTemplate.aggregate(aggregation, StoreWebApp.class, Document.class); + results.forEach((result) -> artifacts.add(result)); + return artifacts; + } + + public StoreWebApp find(UUID fileUuid) { + Query query = Query.query(Criteria.where("_id").is(fileUuid)); + return (StoreWebApp)this.mongoTemplate.findOne(query, StoreWebApp.class); + } + + public StoreWebApp findLatest(String groupId, String artifactId, boolean isFormal) { + Criteria criteria = Criteria.where("appInfo.groupId").is(groupId).and("appInfo.artifactId").is(artifactId).and("fileInfo").exists(true); + if (isFormal) { + criteria.and("isFormal").is(true); + } + + Query query = Query.query(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"appInfo.buildTime"})); + return (StoreWebApp)this.mongoTemplate.findOne(query, StoreWebApp.class); + } + + public StoreWebApp find(String groupId, String artifactId, String version) { + Criteria criteria = new Criteria(); + if (!Strings.isNullOrEmpty(groupId)) { + criteria.and("appInfo.groupId").is(groupId); + } + + if (!Strings.isNullOrEmpty(artifactId)) { + criteria.and("appInfo.artifactId").is(artifactId); + } + + if (!Strings.isNullOrEmpty(version)) { + criteria.and("appInfo.version").is(version); + } + + Query query = Query.query(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"appInfo.buildTime"})); + return (StoreWebApp)this.mongoTemplate.findOne(query, StoreWebApp.class); + } + + public List findAll(String groupId, String artifactId, String version, int limit) { + Criteria criteria = new Criteria(); + if (!Strings.isNullOrEmpty(groupId)) { + criteria.and("appInfo.groupId").is(groupId); + } + + if (!Strings.isNullOrEmpty(artifactId)) { + criteria.and("appInfo.artifactId").is(artifactId); + } + + if (!Strings.isNullOrEmpty(version)) { + criteria.and("appInfo.version").is(version); + } + + Query query = Query.query(criteria); + query.with(Sort.by(Direction.DESC, new String[]{"appInfo.buildTime"})); + if (limit > 0) { + query.limit(limit); + } + + return this.mongoTemplate.find(query, StoreWebApp.class); + } + + public Page find(String groupId, String artifactId, Integer page, Integer size) { + Query query = Query.query(Criteria.where("appInfo.groupId").is(groupId).and("appInfo.artifactId").is(artifactId)); + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, StoreWebApp.class); + query.with(Sort.by(Direction.DESC, new String[]{"appInfo.buildTime"})); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query, StoreWebApp.class); + return new PageImpl(result, pageable, total); + } + + public boolean delete(UUID fileUuid, boolean fileOnly) { + McFile file = new McFile(this.getStoreFilePath(fileUuid)); + file.delete(); + this.cloudStorageService.delete("store", "webapp", fileUuid); + Query query = Query.query(Criteria.where("_id").is(fileUuid)); + if (!fileOnly) { + return this.mongoTemplate.remove(query, StoreWebApp.class).getDeletedCount() > 0L; + } else { + this.mongoTemplate.updateFirst(query, (new Update()).unset("fileInfo"), StoreWebApp.class); + return true; + } + } + + public String getStoreFilePath(UUID uuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"webapp", uuid.toString()}); + } + + public String getStoreTempFilePath(UUID uuid) { + return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"temp", "webapp", uuid.toString()}); + } +} diff --git a/src/main/java/com/midm/service/system/HelpMessageService.java b/src/main/java/com/midm/service/system/HelpMessageService.java new file mode 100644 index 0000000..f52d70b --- /dev/null +++ b/src/main/java/com/midm/service/system/HelpMessageService.java @@ -0,0 +1,168 @@ +package com.midm.service.system; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.system.HelpMessage; +import com.midm.service.Aggregations; +import com.midm.service.BaseService; +import com.midm.service.file.FileService; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.ServletContext; +import org.apache.commons.collections4.MapUtils; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.aggregation.Aggregation; +import org.springframework.data.mongodb.core.aggregation.AggregationOperation; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; + +@Service +public class HelpMessageService extends BaseService { + @Autowired + ServletContext servletContext; + @Autowired + @Qualifier("stringTemplateEngine") + private TemplateEngine stringTemplateEngine; + @Autowired + @Lazy + @Qualifier("fileService") + private FileService fileService; + private final Map messageMap = new HashMap(); + private String helpTemplate; + + public void save(HelpMessage message) { + if (message != null && !Strings.isNullOrEmpty(message.getCode())) { + this.mongoTemplate.save(message, "helpMessage"); + this.messageMap.put(message.getCode(), message); + } + + } + + public Page findMessages(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "code"; + direction = Direction.ASC; + } + + List result = this.find(HelpMessage.class, filter, sortBy, direction); + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public void save(HelpMessage[] messages) { + if (messages != null && messages.length > 0) { + for(HelpMessage message : messages) { + this.save(message); + } + } + + } + + public long save(String code, String locale, String title, String message) { + if (Strings.isNullOrEmpty(code)) { + return 0L; + } else { + Query query = Query.query(Criteria.where("_id").is(code)); + Update update = Update.update(String.format("message.%s.title", locale), title).set(String.format("message.%s.desc", locale), message); + UpdateResult result = this.mongoTemplate.upsert(query, update, HelpMessage.class); + return result.getModifiedCount(); + } + } + + public long delete(String code) { + Query query = Query.query(Criteria.where("_id").is(code)); + DeleteResult result = this.mongoTemplate.remove(query, HelpMessage.class); + return result.getDeletedCount(); + } + + public long saveOption(String code, String category, String key, String desc) { + Query query = Query.query(Criteria.where("_id").is(code)); + Update update = Update.update(String.format("options.%s.%s", category, key), desc); + UpdateResult result = this.mongoTemplate.upsert(query, update, HelpMessage.class); + return result.getModifiedCount(); + } + + public long deleteOption(String code, String category, String key) { + Query query = Query.query(Criteria.where("_id").is(code)); + Update update = (new Update()).unset(String.format("%s.%s", category, key)); + UpdateResult result = this.mongoTemplate.upsert(query, update, HelpMessage.class); + return result.getModifiedCount(); + } + + public HelpMessage get(String code) { + return (HelpMessage)this.messageMap.get(code); + } + + public String getTitle(String code) { + return this.getTitle(code, "en-US"); + } + + public String getTitle(String code, String locale) { + HelpMessage message = this.get(code); + return message == null ? null : message.getTitle(locale); + } + + public String getOptionsAsMap(String code) { + HelpMessage message = this.get(code); + return McJsonUtils.toJson(message.getOptions(), true); + } + + public String getHtmlContent(String code, String locale) { + HelpMessage message = this.get(code); + if (message == null) { + this.save(new HelpMessage(code)); + return ""; + } else if (!message.getMessage().isEmpty()) { + Context context = new Context(); + context.setVariable("description", message.getDescription(locale)); + context.setVariable("options", message.getOptions()); + return this.stringTemplateEngine.process(this.helpTemplate, context); + } else { + return ""; + } + } + + public List getOptionCategories() { + AggregationOperation optionProjectOp = Aggregations.newOperation("{$project: {options: {$objectToArray: '$options'}}}"); + AggregationOperation categoryProjectOp = Aggregations.newOperation("{$project: {category: '$options.k'}}"); + AggregationOperation unwindOp = Aggregation.unwind("category"); + AggregationOperation groupOp = Aggregations.newOperation("{$group: {_id: null, categories: {$addToSet: '$category'}}}"); + Document result = (Document)this.mongoTemplate.aggregate(Aggregation.newAggregation(new AggregationOperation[]{optionProjectOp, categoryProjectOp, unwindOp, groupOp}), HelpMessage.class, Document.class).getUniqueMappedResult(); + return (List)(result == null ? new ArrayList() : (List)result.get("categories")); + } + + public boolean exists(String code) { + HelpMessage message = this.get(code); + if (message == null) { + message = new HelpMessage(code); + this.save(message); + } + + return !message.getMessage().isEmpty(); + } + + public void loadMessages() { + List messages = this.mongoTemplate.findAll(HelpMessage.class); + this.messageMap.clear(); + MapUtils.populateMap(this.messageMap, messages, HelpMessage::getCode); + this.helpTemplate = this.fileService.getResourceToString("help/helpMessage.html", false); + } +} diff --git a/src/main/java/com/midm/service/system/HostLicenseService.java b/src/main/java/com/midm/service/system/HostLicenseService.java new file mode 100644 index 0000000..dd04812 --- /dev/null +++ b/src/main/java/com/midm/service/system/HostLicenseService.java @@ -0,0 +1,419 @@ +package com.midm.service.system; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.device.Device; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.model.system.HostLicense; +import com.midm.model.system.StandaloneLicense; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.news.NewsMessageService; +import com.midm.service.org.UserService; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.utils.McStringUtils; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import javax.mail.internet.InternetAddress; +import org.joda.time.DateTime; +import org.joda.time.Days; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.data.support.PageableExecutionUtils; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +public class HostLicenseService extends BaseService { + public static final String KEY_IS_PRIMARY = "isPrimary"; + public static final String KEY_LICENSE_KEY = "licenseKey"; + @Autowired + @Lazy + private UserService userService; + @Autowired + private NewsMessageService newsMessageService; + @Autowired + private SettingsService settingsService; + @Autowired + private LicenseService deviceLicenseService; + @Autowired + private WebSocketSessionManager sessionManager; + @Autowired + private EmailService emailService; + @Value("${system.hash:#{null}}") + private String systemHash; + private HostLicense primaryLicense = null; + + public HostLicense save(String systemHash, String licenseKey, boolean isPrimary) { + HostLicense license = new HostLicense(this.settingsService.hostId(), systemHash, licenseKey); + license.setPrimary(isPrimary); + return license.isValidKey() ? this.save(license) : null; + } + + public HostLicense save(HostLicense license) { + if (license != null) { + if (Strings.isNullOrEmpty(this.systemHash)) { + this.systemHash = HostLicense.generateSystemHash(this.systemHash); + } + + license.setHostId(this.settingsService.hostId()); + if (this.systemHash.equals(license.getSystemHash())) { + license.validate(); + } + + if (!license.isPrimary() && this.mongoTemplate.count(Query.query(Criteria.where("isPrimary").exists(true)), HostLicense.class) == 0L) { + license.setPrimary(true); + } + + if (license.isPrimary()) { + this.unsetPrimary(license.getSystemHash()); + this.primaryLicense = license; + } + + return (HostLicense)this.saveDocument(license); + } else { + return null; + } + } + + public Site getCurrentSite(UUID siteUuid) { + return (Site)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(siteUuid)), Site.class); + } + + public void save(StandaloneLicense standaSettings) { + this.mongoTemplate.save(standaSettings); + } + + public void sendMessageToRecipients(StandaloneLicense standaSettings) { + Site site = standaSettings.getSite(); + NewsMessage message = new NewsMessage(); + message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); + message.setCategory("host_license"); + message.setForWhat("license key requested"); + String title = "[Host License]"; + String format = "Host license key requested at %s"; + message.getReference().put("siteIdName", site.getIdName()); + title = title + " Requested"; + format = format + " by." + site.getIdName(); + message.getMessage("en-US").put("title", title); + String content = String.format(format, (new SimpleDateFormat()).format(standaSettings.getCreated())); + message.getMessage("en-US").put("content", content); + message.getMessage("en-US").put("summary", content); + this.newsMessageService.save(message); + InternetAddress[] recipients = this.settingsService.siteRequestRecipients(); + if (recipients != null) { + String licenseType = standaSettings.getLicenseType(); + int deviceLimit = standaSettings.getDeviceLimit(); + long validTo = standaSettings.getValidTo(); + int period = standaSettings.getPeriod() == null ? -1 : standaSettings.getPeriod(); + + for(InternetAddress user : recipients) { + this.sendMessageToRecipients(user.getAddress(), message, site, licenseType, deviceLimit, validTo, period); + } + } + + } + + public void sendMessageToRecipients(String email, NewsMessage message, Site site, String licenseType, int deviceLimit, long validTo, int period) { + if (email != null) { + DateFormat dateFormat = new SimpleDateFormat("EE-MM-dd-yyyy"); + if (validTo == -1L) { + message.getReference().put("validTo", validTo); + message.getReference().put("period", period); + } else { + message.getReference().put("validTo", dateFormat.format(new Date(validTo))); + } + + message.getReference().put("deviceLimit", deviceLimit); + message.getReference().put("licenseType", licenseType); + this.emailService.sendHostLicenseRequestNoti(email, message); + } + } + + public void sendMessage(StandaloneLicense standaSettings) { + Site site = standaSettings.getSite(); + NewsMessage message = new NewsMessage(); + message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); + message.setCategory("host_license"); + message.setForWhat("license key generated"); + String title = "[Host License]"; + String format = "Host license key requested at %s"; + message.getReference().put("siteIdName", site.getIdName()); + title = title + " Generated"; + format = format + " generated successfully."; + message.getMessage("en-US").put("title", title); + String content = String.format(format, (new SimpleDateFormat()).format(standaSettings.getCreated())); + message.getMessage("en-US").put("content", content); + message.getMessage("en-US").put("summary", content); + this.newsMessageService.save(message); + List users = this.userService.findSupervisors(site.getUuid()); + String licenseType = standaSettings.getLicenseType(); + int deviceLimit = standaSettings.getDeviceLimit(); + long validTo = standaSettings.getValidTo(); + users.forEach((user) -> this.sendMessage(user, message, site, licenseType, deviceLimit, validTo)); + } + + public void sendMessage(User user, NewsMessage message, Site site, String licenseType, int deviceLimit, long validTo) { + if (user.getEnabled()) { + this.newsMessageService.setMessageLog(message, user, site); + if (this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.sendMessageToOnlineUsers((User)user, 119); + } + + DateFormat dateFormat = new SimpleDateFormat("EE-MM-dd-yyyy"); + if (validTo == -1L) { + message.getReference().put("validTo", validTo); + } else { + message.getReference().put("validTo", dateFormat.format(new Date(validTo))); + } + + message.getReference().put("deviceLimit", deviceLimit); + message.getReference().put("licenseType", licenseType); + this.emailService.sendHostLicenseNoti(user, message); + } + } + + public HostLicense setAsPrimary(String systemHash) { + HostLicense license = (HostLicense)this.findById(HostLicense.class, systemHash); + if (license != null && !license.isPrimary()) { + this.unsetPrimary(systemHash); + license.setHostId(this.settingsService.hostId()); + license.setAsTrial(); + DateTime primaryValidated = new DateTime(this.primaryLicense.validatedDate()); + license.setValidFrom(primaryValidated.getMillis()); + license.setValidTo(primaryValidated.plusDays(45).getMillis()); + license.generateLicense(); + license.setPrimary(true); + license.dispatch(); + this.primaryLicense = license; + return this.save(license); + } else { + return null; + } + } + + public boolean isStandalone() { + return this.getPrimaryLicense().isStandalone(); + } + + public int getDeviceLimit() { + return this.getPrimaryLicense().getDeviceLimit(); + } + + public long deviceLeft() { + return (long)this.getDeviceLimit() - this.count(Device.class); + } + + public Long validTo() { + return this.getPrimaryLicense().getValidTo(); + } + + public boolean isValid() { + return this.getPrimaryLicense().isValid(); + } + + public String getSystemHash() { + return HostLicense.generateSystemHash(this.systemHash); + } + + public HostLicense find(String systemHash) { + return (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(systemHash)), HostLicense.class); + } + + public StandaloneLicense findLatest(UUID uuid) { + return (StandaloneLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("site.$id").is(uuid)), StandaloneLicense.class); + } + + public void deleteStandaloneLicense(UUID siteUuid) { + this.mongoTemplate.remove(Query.query(Criteria.where("site.$id").is(siteUuid)), StandaloneLicense.class); + } + + public HostLicense getPrimaryLicense() { + if (this.primaryLicense == null) { + HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class); + if (license != null) { + license.setHostId(this.settingsService.hostId()); + if (!license.hasLicenseKey()) { + license = this.generateTrialLicense(license.getSystemHash()); + this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(license.getSystemHash())), Update.update("licenseKey", license.getLicenseKey()), HostLicense.class); + } else { + license.setHostId(this.settingsService.hostId()); + license.dispatch(); + } + } else { + license = (HostLicense)this.mongoTemplate.findOne(new Query(), HostLicense.class); + if (license == null) { + license = this.generateTrialLicense(HostLicense.generateSystemHash((String)null)); + } else if (!license.hasLicenseKey()) { + license = this.generateTrialLicense(HostLicense.generateSystemHash(license.getSystemHash())); + } + + license.setPrimary(true); + this.save(license); + } + + this.primaryLicense = license; + } + + return this.primaryLicense; + } + + private HostLicense generateTrialLicense(String systemHash) { + HostLicense license = new HostLicense(this.settingsService.hostId(), systemHash); + license.setValidFrom(this.settingsService.startedFrom()); + license.setAsTrial(); + license.generateLicense(); + return license; + } + + private HostLicense validate(String systemHash) { + HostLicense license = (HostLicense)this.findById(HostLicense.class, systemHash); + if (license == null) { + license = new HostLicense(this.settingsService.hostId(), systemHash); + if (this.count(HostLicense.class) == 0L) { + license.setPrimary(true); + license.setAsTrial(); + long startsFrom = this.settingsService.startedFrom(); + if (startsFrom > 0L) { + DateTime trialEnd = (new DateTime(startsFrom)).plusDays(HostLicense.trialPeriod); + if (trialEnd.isBefore(license.getValidTo())) { + license.setValidTo(trialEnd.getMillis()); + } + } + + license.generateLicense(); + } + } else { + license.setHostId(this.settingsService.hostId()); + license.dispatch(); + } + + return this.save(license); + } + + public List findAll() { + return this.findAll(HostLicense.class); + } + + public void delete(String systemHash) { + HostLicense license = (HostLicense)this.findById(HostLicense.class, systemHash); + if (license != null && !license.isPrimary()) { + this.deleteById(HostLicense.class, systemHash); + } + + } + + private void unsetPrimary(String systemHash) { + Criteria criteria = Criteria.where("_id").ne(systemHash); + Update update = (new Update()).unset("licenseKey").set("isPrimary", false); + this.mongoTemplate.updateMulti(Query.query(criteria), update, HostLicense.class); + } + + public boolean isPrimaryServer() { + HostLicense license = (HostLicense)this.findById(HostLicense.class, HostLicense.generateSystemHash(this.systemHash)); + return license != null && license.isPrimary(); + } + + public boolean isExceedDeviceLimit() { + int limit = this.getPrimaryLicense().getDeviceLimit(); + return limit != -1 && (long)limit <= this.count(Device.class); + } + + public HostLicense validateLicense(String hostId, String systemHash, String licenseKey) { + if (Strings.isNullOrEmpty(hostId)) { + hostId = this.settingsService.hostId(); + } + + HostLicense license = new HostLicense(hostId, systemHash, licenseKey); + license.dispatch(); + return license; + } + + public void validateLicense() { + if (this.primaryLicense == null) { + this.getPrimaryLicense(); + } + + if (!this.isStandalone()) { + this.deviceLicenseService.getAllModels(); + } + + this.validate(HostLicense.generateSystemHash(this.systemHash)); + } + + public void notifyIfExpiring() { + HostLicense license = this.getPrimaryLicense(); + if (license.getSystemHash().equals(HostLicense.generateSystemHash((String)null))) { + if (license.isValid()) { + DateTime validTo = new DateTime(license.getValidTo()); + int daysLeft = Days.daysBetween(DateTime.now().withTimeAtStartOfDay(), validTo).getDays(); + if (daysLeft >= 0 && daysLeft <= 30 && daysLeft % 3 == 0) { + List systemAdmins = this.userService.findSystemAdmin(); + String subject = "MiDM host license is about to expired"; + String content = String.format("MiDM host license is about to expired within %s days", daysLeft); + + for(User admin : systemAdmins) { + if (admin.getEnabled()) { + this.emailService.sendStandaloneMessage("MiDM host license is about to expired", admin, content); + } + } + + } + } + } + } + + public Page find(JsonObject filter, Integer page, UUID siteUuid, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "site.idName"; + direction = Direction.ASC; + } + + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + if (siteUuid != null) { + query.addCriteria(Criteria.where("site.$id").is(siteUuid)); + } + + Pageable pageable = PageRequest.of(page, size); + query.with(pageable); + List result = this.mongoTemplate.find(query, StandaloneLicense.class); + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, StandaloneLicense.class); + Page pageResult = PageableExecutionUtils.getPage(result, pageable, McMongoUtils.toTotalSupplier(total)); + return pageResult; + } + + @Scheduled( + cron = "0 0 0 * * *" + ) + @Async + protected void scheduleMaintenance() { + this.validateLicense(); + this.notifyIfExpiring(); + } + + @Scheduled( + cron = "0 15,45 * * * *" + ) + @Async + protected void scheduleToForceGC() { + System.gc(); + } +} diff --git a/src/main/java/com/midm/service/system/LicenseService.java b/src/main/java/com/midm/service/system/LicenseService.java new file mode 100644 index 0000000..bb2d9d7 --- /dev/null +++ b/src/main/java/com/midm/service/system/LicenseService.java @@ -0,0 +1,153 @@ +package com.midm.service.system; + +import com.google.api.client.util.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.system.Category; +import com.midm.model.system.CategoryId; +import com.midm.model.system.LicenseFeature; +import com.midm.model.system.LicenseModel; +import com.midm.service.BaseService; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.utils.McStringUtils; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class LicenseService extends BaseService { + private List licenseModels = null; + Map modelsByUuid = new HashMap(); + Map modelsByIdName = new HashMap(); + private LicenseModel trialLicenseModel = null; + + public List getFullFeatures() { + List categories = this.getCategories(); + + for(Category category : categories) { + List features = this.getFeatures(category.getCategoryId()); + category.setFeatures(features); + } + + return categories; + } + + public List getCategories() { + Query query = Query.query(Criteria.where("categoryId.use").is("licenseFeature")); + query.with(Sort.by(Direction.ASC, new String[]{"order"})); + return this.mongoTemplate.find(query, Category.class); + } + + public Category save(Category category) { + return (Category)this.saveDocument(category); + } + + public void delete(Category category) { + this.delete(category.id); + } + + public void delete(CategoryId categoryId) { + this.deleteById(Category.class, categoryId); + } + + public void deleteCategory(String categoryId) { + CategoryId id = new CategoryId("licenseFeature", categoryId); + Query query = Query.query(Criteria.where("categoryId").is(id)); + this.mongoTemplate.remove(query, LicenseFeature.class); + this.delete(id); + } + + public List getFeatures(String categoryId) { + CategoryId id = new CategoryId("licenseFeature", categoryId); + Query query = Query.query(Criteria.where("categoryId").is(id)); + return this.mongoTemplate.find(query, LicenseFeature.class); + } + + public LicenseFeature save(LicenseFeature feature) { + return (LicenseFeature)this.saveDocument(feature); + } + + public void deleteFeature(String featureCode) { + this.deleteById(LicenseFeature.class, featureCode); + } + + public LicenseModel findLicenseModelByUuid(UUID modelUuid) { + return modelUuid != null ? (LicenseModel)this.modelsByUuid.get(modelUuid) : this.getTrialLicenseModel(); + } + + public LicenseModel findLicenseModelByIdName(String idName) { + return !Strings.isNullOrEmpty(idName) ? (LicenseModel)this.modelsByIdName.get(idName) : null; + } + + public LicenseModel getTrialLicenseModel() { + if (this.trialLicenseModel == null) { + this.trialLicenseModel = this.findLicenseModelByIdName("trial"); + if (this.trialLicenseModel == null) { + LicenseModel licenseModel = (LicenseModel)this.mongoTemplate.findOne(Query.query(Criteria.where("type").is('t')), LicenseModel.class); + this.trialLicenseModel = licenseModel != null ? licenseModel : LicenseModel.defaultTrial(); + } + } + + return this.trialLicenseModel; + } + + public List getAllModels() { + if (this.licenseModels == null) { + this.licenseModels = this.findAll(LicenseModel.class); + this.modelsByUuid.clear(); + this.modelsByIdName.clear(); + this.licenseModels.forEach((model) -> { + this.modelsByUuid.put(model.getUuid(), model); + this.modelsByIdName.put(model.getIdName(), model); + }); + } + + return this.licenseModels; + } + + public Page findModels(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "name"; + direction = Direction.ASC; + } + + Query query = McMongoUtils.toQuery(filter, sortBy, direction); + query.collation(LocaleConst.COLLATION_DEFAULT); + long total = this.mongoTemplate.count(query, LicenseModel.class); + Pageable pageable = PageRequest.of(page, size); + List result = this.mongoTemplate.find(query.with(pageable), LicenseModel.class); + Page pageResult = new PageImpl(result, pageable, total); + return pageResult; + } + + public LicenseModel save(LicenseModel model) { + if (model.getUuid() == null) { + model.initUuid(); + } + + model = (LicenseModel)this.saveDocument(model); + this.licenseModels = null; + this.getAllModels(); + return model; + } + + public void delete(LicenseModel model) { + this.deleteModel(model.getUuid()); + } + + public void deleteModel(UUID modelUuid) { + this.deleteById(LicenseModel.class, modelUuid); + this.licenseModels = null; + this.getAllModels(); + } +} diff --git a/src/main/java/com/midm/service/system/LocaleService.java b/src/main/java/com/midm/service/system/LocaleService.java new file mode 100644 index 0000000..35592b6 --- /dev/null +++ b/src/main/java/com/midm/service/system/LocaleService.java @@ -0,0 +1,174 @@ +package com.midm.service.system; + +import com.google.api.client.util.Strings; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.system.AltLocale; +import com.midm.model.system.ResourceLocale; +import com.midm.model.system.ResourceMessage; +import com.midm.service.BaseService; +import com.mitac.cell.db.util.McDbUtils; +import com.mitac.cell.utils.McStringUtils; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class LocaleService extends BaseService { + private Map messageMap; + private Map localeMap; + private Set enabledLocaleTags = new HashSet(); + private List enabledLocales; + + public void save(ResourceLocale locale) { + this.saveDocument(locale); + this.addIndex("resourceMessage", new String[]{"messages." + locale.getLocale()}); + this.enabledLocales = null; + } + + public List findAllLocales() { + return this.findAll(ResourceLocale.class); + } + + public List findEnabledLocales() { + if (this.enabledLocales == null || this.enabledLocales.isEmpty()) { + Sort sort = Sort.by(Direction.ASC, new String[]{"order"}).and(Sort.by(Direction.ASC, new String[]{"locale"})); + Query query = Query.query(Criteria.where("enabled").is(true)); + query.with(sort); + this.enabledLocales = this.mongoTemplate.find(query, ResourceLocale.class); + this.enabledLocaleTags.clear(); + this.enabledLocales.forEach((locale) -> this.enabledLocaleTags.add(locale.getLocale())); + } + + return this.enabledLocales; + } + + private boolean isLocaleEnabled(String localeTag) { + return this.enabledLocaleTags.contains(localeTag); + } + + public Page findLocales(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + List result = this.find(ResourceLocale.class, filter, sortBy, direction); + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public void delete(ResourceLocale locale) { + this.deleteById(ResourceLocale.class, locale.getLocale()); + + try { + this.unset("resourceMessage", "messages." + locale.getLocale()); + } catch (Exception var3) { + } + + this.enabledLocales = null; + } + + public void save(AltLocale altLocale) { + this.localeMap.put(altLocale.getLocale(), altLocale); + this.saveDocument(altLocale); + } + + public Locale findAltLocale(Locale locale) { + return this.findAltLocale(locale.toLanguageTag()); + } + + public Locale findAltLocale(String localeTag) { + if (this.isLocaleEnabled(localeTag)) { + return Locale.forLanguageTag(localeTag); + } else if (this.localeMap != null && this.localeMap.containsKey(localeTag)) { + AltLocale altLocale = (AltLocale)this.localeMap.get(localeTag); + return this.isLocaleEnabled(altLocale.getAltLocale()) ? altLocale.toLocale() : LocaleConst.DEFAULT_LOCALE; + } else { + return LocaleConst.DEFAULT_LOCALE; + } + } + + public List findAllAltLocales() { + return this.findAll(AltLocale.class); + } + + public Page findAltLocales(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + if (McStringUtils.isNullOrEmpty(sortBy)) { + sortBy = "locale"; + direction = Direction.ASC; + } + + List result = this.find(AltLocale.class, filter, sortBy, direction); + if (page * size >= result.size()) { + page = 0; + } + + return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); + } + + public void delete(AltLocale altLocale) { + this.localeMap.remove(altLocale.getLocale()); + this.deleteById(AltLocale.class, altLocale.getLocale()); + } + + public void loadLocaleAndResources() { + this.localeMap = (Map)this.findAllAltLocales().stream().collect(Collectors.toMap(AltLocale::getLocale, (locale) -> locale)); + this.messageMap = (Map)this.findAllMessages().stream().collect(Collectors.toMap(ResourceMessage::getCode, (value) -> value)); + } + + public ResourceMessage save(String code, String locale, String message) { + ResourceMessage resourceMessage = (ResourceMessage)this.findById(ResourceMessage.class, code); + if (resourceMessage == null) { + resourceMessage = new ResourceMessage(code); + } + + resourceMessage.setMessage(locale, message); + return this.save(resourceMessage); + } + + public ResourceMessage save(ResourceMessage message) { + if (Strings.isNullOrEmpty(message.getCode())) { + return null; + } else { + String key = message.getCode(); + this.messageMap.put(key, message); + return (ResourceMessage)this.saveDocument(message); + } + } + + public ResourceMessage getMessage(String code) { + return (ResourceMessage)this.messageMap.get(code); + } + + public String getMessage(Locale locale, String code) { + return this.getMessage(locale.toLanguageTag(), code); + } + + public String getMessage(String locale, String code) { + ResourceMessage resourceMessage = (ResourceMessage)this.messageMap.get(code); + if (resourceMessage == null) { + resourceMessage = (ResourceMessage)this.saveDocument(new ResourceMessage(code)); + } + + return resourceMessage.getMessage(locale); + } + + public List findAllMessages() { + return this.findAll(ResourceMessage.class); + } + + public void delete(ResourceMessage message) { + this.messageMap.remove(message.getCode()); + this.deleteById(ResourceMessage.class, message.getCode()); + } + + public ResourceMessage findById(String code) { + return (ResourceMessage)this.findById(ResourceMessage.class, code); + } +} diff --git a/src/main/java/com/midm/service/system/PolicyAgreementService.java b/src/main/java/com/midm/service/system/PolicyAgreementService.java new file mode 100644 index 0000000..c571357 --- /dev/null +++ b/src/main/java/com/midm/service/system/PolicyAgreementService.java @@ -0,0 +1,70 @@ +package com.midm.service.system; + +import com.midm.constant.LocaleConst; +import com.midm.model.system.PolicyAgreement; +import com.midm.service.BaseService; +import com.mitac.cell.db.util.McMongoUtils; +import java.util.List; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class PolicyAgreementService extends BaseService { + public boolean hasEula(String category) { + Criteria criteria = Criteria.where("category").is(category); + return this.mongoTemplate.count(Query.query(criteria), PolicyAgreement.class) > 0L; + } + + public PolicyAgreement save(PolicyAgreement agreement) { + return (PolicyAgreement)this.saveDocument(agreement); + } + + public PolicyAgreement findExistAgreement(String category, String version) { + Query query = Query.query(Criteria.where("category").is(category).and("version").is(version)); + return (PolicyAgreement)this.mongoTemplate.findOne(query, PolicyAgreement.class); + } + + public Page findAll(String filter, Integer page, Integer size) { + Query query = new Query(); + query.collation(LocaleConst.COLLATION_DEFAULT); + Long total = this.mongoTemplate.count(query, PolicyAgreement.class); + Pageable pageable = PageRequest.of(page, size); + String sortBy = "created"; + String direction = "DESC"; + Sort sort = Sort.by(Direction.valueOf(direction.trim().toUpperCase()), new String[]{sortBy}); + if (sort != null) { + query.with(sort); + } + + Criteria criteriaFilter = McMongoUtils.toCriteria(filter); + query.addCriteria(criteriaFilter); + List result = this.mongoTemplate.find(query.with(pageable), PolicyAgreement.class); + Page pageResult = new PageImpl(result, pageable, total); + return pageResult; + } + + public PolicyAgreement findlatest(String category) { + Criteria criteria = Criteria.where("category").is(category); + Query query = new Query(criteria); + String sortBy = "created"; + String direction = "DESC"; + Sort sort = Sort.by(Direction.valueOf(direction.trim().toUpperCase()), new String[]{sortBy}); + if (sort != null) { + query.with(sort); + } + + PolicyAgreement result = (PolicyAgreement)this.mongoTemplate.findOne(query, PolicyAgreement.class); + return result; + } + + public void delete(PolicyAgreement agreement) { + this.deleteById(PolicyAgreement.class, agreement.getUuid()); + } +} diff --git a/src/main/java/com/midm/service/system/RestoreService.java b/src/main/java/com/midm/service/system/RestoreService.java new file mode 100644 index 0000000..9f9d43f --- /dev/null +++ b/src/main/java/com/midm/service/system/RestoreService.java @@ -0,0 +1,179 @@ +package com.midm.service.system; + +import com.google.common.base.Strings; +import com.midm.model.message.MidmResponse; +import com.midm.service.BaseService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import com.mongodb.client.MongoCollection; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.HttpClientBuilder; +import org.bson.BSONDecoder; +import org.bson.BSONObject; +import org.bson.BasicBSONDecoder; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class RestoreService extends BaseService { + @Autowired + private SettingsService settingsService; + @Autowired + private LocaleService localeService; + @Autowired + private HelpMessageService helpMessageService; + + public void restore(McFile source) { + if (source != null && source.exists()) { + if (source.isFile()) { + if (source.getName().endsWith(".bson")) { + InputStream input = new BufferedInputStream(source.getInputStream()); + this.restore(input, source.getNameWithoutExtension()); + + try { + input.close(); + } catch (IOException var9) { + } + } else if (source.getName().endsWith(".zip")) { + try { + ZipInputStream input = new ZipInputStream(source.getInputStream()); + this.restore(input); + input.close(); + } catch (IOException var8) { + } + } else if (source.getName().endsWith(".gz")) { + try { + GZIPInputStream input = new GZIPInputStream(source.getInputStream()); + this.restore((InputStream)input); + input.close(); + } catch (IOException var7) { + } + } + } else { + File[] files = source.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(".bson"); + } + }); + + for(File aFile : files) { + this.restore(new McFile(aFile)); + } + } + } + + } + + public void restore(String syncServer) { + try { + if (Strings.isNullOrEmpty(syncServer)) { + syncServer = this.settingsService.getSyncServer(); + } + + HttpClient client = HttpClientBuilder.create().build(); + URI uri = (new URIBuilder(syncServer)).setPath("api/store/others/findBy").addParameter("alias", "midmResourceDB.zip").build(); + HttpResponse response = client.execute(new HttpGet(uri)); + MidmResponse midmResponse = (MidmResponse)McJsonUtils.toObject(response.getEntity().getContent(), MidmResponse.class); + DbObject data = midmResponse.getDataAsDbObject(); + long lastModified = data.getDbObject(new String[]{"fileInfo"}).getLong("lastModified"); + long dbUpdated = this.settingsService.resourceDbUpdated(); + if (dbUpdated > 0L && lastModified == dbUpdated) { + return; + } + + uri = (new URIBuilder(syncServer)).setPath("store/other/midmResourceDB.zip").build(); + response = client.execute(new HttpGet(uri)); + this.restore(response.getEntity().getContent()); + this.settingsService.setDbUpdated(lastModified); + } catch (IOException var11) { + } catch (URISyntaxException var12) { + } + + } + + public void restore(InputStream input) { + ZipInputStream zipInput = new ZipInputStream(input); + this.restore(zipInput); + + try { + zipInput.close(); + input.close(); + } catch (IOException var4) { + } + + this.reloadResources(); + } + + public void restore(ZipInputStream input) { + ZipEntry entry; + try { + for(entry = null; (entry = input.getNextEntry()) != null; input.closeEntry()) { + if (!entry.isDirectory()) { + String fileName = entry.getName(); + int startIndex = fileName.lastIndexOf("/") + 1; + int endIndex = fileName.indexOf(".bson"); + if (endIndex > 0) { + String collectionName = fileName.substring(startIndex, endIndex); + this.restore(input, collectionName); + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public int restore(InputStream input, String collectionName) { + int count = 0; + + try { + MongoCollection collection = this.getCollection(collectionName); + BSONDecoder decoder = new BasicBSONDecoder(); + List records = new ArrayList(); + + while(input.available() > 0) { + try { + BSONObject bson = decoder.readObject(input); + ++count; + records.add(new Document(bson.toMap())); + } catch (Exception var8) { + } + } + + if (count > 0) { + collection.drop(); + collection.insertMany(records); + } + } catch (IOException e) { + e.printStackTrace(); + } + + return count; + } + + public void backup() { + } + + public void reloadResources() { + this.localeService.loadLocaleAndResources(); + this.helpMessageService.loadMessages(); + } +} diff --git a/src/main/java/com/midm/service/system/SettingsService.java b/src/main/java/com/midm/service/system/SettingsService.java new file mode 100644 index 0000000..d15ae85 --- /dev/null +++ b/src/main/java/com/midm/service/system/SettingsService.java @@ -0,0 +1,360 @@ +package com.midm.service.system; + +import com.google.common.base.Strings; +import com.midm.MainApplication; +import com.midm.model.org.User; +import com.midm.model.system.SystemSetting; +import com.midm.service.BaseService; +import com.midm.service.EmailService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.DeviceService; +import com.mitac.cell.db.util.McMongoUtils; +import com.mitac.cell.net.McNetUtils; +import com.mitac.cell.utils.McNumberUtils; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import org.apache.commons.collections4.MapUtils; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class SettingsService extends BaseService { + private static final String DEFAULT_SYNC_SERVER = "https://midmtest.mic.com.tw"; + private static final String KEY_HOST_ID = "host.id"; + private static final String KEY_MIDM_LICENSE = "midm.license"; + public static final String KEY_DB_INDEXED = "db.indexed"; + public static final String KEY_DB_SCHEME = "db.scheme"; + public static final String KEY_DB_SYNC_SERVER = "db.sync.server"; + public static final String KEY_DB_SYNC_ON_STARTS = "db.sync.onStarts"; + public static final String KEY_DB_SYNC_UPDATED = "db.sync.updated"; + public static final String KEY_RTC_AWS_ARN = "rtc.aws.arn"; + public static final String KEY_URL_VALIDATE_RSA = "url.validate.rsa"; + @Value("${files.root:/MiDM/files}") + private String filesRootDefault; + @Autowired + private PolicyAgreementService policyAgreementService; + @Autowired + @Lazy + private DeviceService deviceService; + @Autowired + @Lazy + private HostLicenseService licenseService; + @Autowired + @Lazy + private CloudStorageService cloudStorageService; + @Autowired + @Lazy + private EmailService emailService; + @Autowired + @Lazy + private RestoreService restoreService; + private String hostId; + private int websocketBufferSize = 65536; + private Map settingsMap = new HashMap(); + + public boolean save(SystemSetting... settings) { + boolean isSucceed = true; + + for(SystemSetting setting : settings) { + String key = setting.getKey(); + if (this.settingsMap.containsKey(key)) { + String value = (String)this.settingsMap.get(key); + String newValue = setting.getValue(); + if (value != null && value.equals(newValue)) { + continue; + } + } + + this.save(setting); + if (key.equalsIgnoreCase("host.id")) { + this.hostId = setting.getValue(); + } else if (key.equalsIgnoreCase("websocket.buffer_size")) { + this.websocketBufferSize = setting.getAsInteger() * 1024; + } else if (key.startsWith("db.deviceReport")) { + this.reindex("deviceReport"); + } else if (key.startsWith("db.midmLog")) { + this.reindex("midmLog"); + } else if (key.equalsIgnoreCase("files.maxUploadSize")) { + MainApplication.restart(); + } else if (key.equalsIgnoreCase("db.sync.onStarts") && this.syncOnStarts() == setting.getAsBoolean()) { + this.restoreService.restore((String)null); + } + } + + this.cloudStorageService.refresh(); + this.emailService.updateMailSender(); + return isSucceed; + } + + public SystemSetting save(String key, String value) { + return this.save(new SystemSetting(key, value)); + } + + public SystemSetting save(String key, Number value) { + return this.save(key, value.toString()); + } + + public SystemSetting save(String key, boolean value) { + return this.save(key, String.valueOf(value)); + } + + public SystemSetting save(String key, Date value) { + return this.save(key, (Number)value.getTime()); + } + + public SystemSetting save(SystemSetting setting) { + this.settingsMap.put(setting.getKey(), setting.getValue()); + return (SystemSetting)this.mongoTemplate.save(setting); + } + + public String hostId() { + if (Strings.isNullOrEmpty(this.hostId)) { + this.hostId = this.get("host.id"); + } + + if (Strings.isNullOrEmpty(this.hostId)) { + this.hostId = "midm." + McNetUtils.hostName(); + this.save("host.id", this.hostId); + } + + return this.hostId; + } + + public long startedFrom() { + long from = this.getLong("midm.startsFrom", -1L); + if (from <= 0L) { + from = this.getFirstUserCreated(); + this.save("midm.startsFrom", (Number)from); + } + + return from; + } + + private Long getFirstUserCreated() { + Query query = new Query(Criteria.where("created").exists(true)); + query.fields().include("created"); + query.with(Sort.by(Direction.ASC, new String[]{"created"})); + User user = (User)this.mongoTemplate.findOne(query, User.class); + return user != null ? user.getCreated().getTime() : (new Date()).getTime(); + } + + public Long validTo() { + return this.licenseService.validTo(); + } + + public int getDeviceLimit() { + return this.licenseService.getDeviceLimit(); + } + + public long deviceLeft() { + return this.licenseService.deviceLeft(); + } + + public boolean isExceedDeviceLimit() { + return this.deviceService.isExceedDeviceLimit(); + } + + public boolean aboutExceedDeviceLimit() { + long deviceLimit = (long)this.getDeviceLimit(); + long deviceLeft = this.deviceLeft(); + return deviceLimit != -1L && deviceLeft <= 30L && deviceLeft > 0L; + } + + public boolean hasDeviceLimit() { + return this.isStandalone() && this.getDeviceLimit() > 0; + } + + public boolean isHostLicenseValid() { + return this.licenseService.isValid(); + } + + public boolean isStandalone() { + return this.licenseService.isStandalone(); + } + + public String getSystemHash() { + return this.licenseService.getSystemHash(); + } + + public boolean eulaEnabled() { + return this.getBoolean("eulaEnabled"); + } + + public boolean rsaEnabled() { + return this.getBoolean("rsaEnabled", false); + } + + public boolean willExpired() { + Long validTo = this.validTo(); + return validTo != null && validTo > 0L; + } + + public int webSocketBufferSize() { + return this.websocketBufferSize; + } + + public boolean exists(String key) { + return Strings.isNullOrEmpty(key) ? false : this.settingsMap.containsKey(key); + } + + public long dbScheme() { + return this.getLong("db.scheme", -1L); + } + + public void setDbScheme(long scheme) { + this.save("db.scheme", (Number)scheme); + } + + public InternetAddress[] siteRequestRecipients() { + String receipients = this.get("recipients.siteRequest"); + + try { + return Strings.isNullOrEmpty(receipients) ? null : InternetAddress.parse(receipients); + } catch (AddressException var3) { + return null; + } + } + + public boolean has(String key) { + if (this.settingsMap.containsKey(key)) { + return !Strings.isNullOrEmpty((String)this.settingsMap.get(key)); + } else { + return false; + } + } + + public String get(String key) { + if (Strings.isNullOrEmpty(key)) { + return ""; + } else { + String value = (String)this.settingsMap.get(key); + if (!Strings.isNullOrEmpty(value)) { + return value; + } else if (key.equals("files.root")) { + this.save(key, this.filesRootDefault); + return this.filesRootDefault; + } else if (key.equals("midm.license")) { + return this.licenseService.getPrimaryLicense().getLicenseKey(); + } else if (key.equals("db.sync.server")) { + return "https://midmtest.mic.com.tw"; + } else { + SystemSetting setting = (SystemSetting)this.findById(SystemSetting.class, key); + if (setting != null) { + this.settingsMap.put(key, setting.getValue()); + return setting.getValue(); + } else { + this.settingsMap.put(key, (Object)null); + return ""; + } + } + } + } + + public String get(String key, String defaultValue) { + String value = (String)this.settingsMap.get(key); + return Strings.isNullOrEmpty(value) ? defaultValue : value; + } + + public Iterable get(String[] keys) { + ArrayList settings = new ArrayList(); + + for(String key : keys) { + String value = this.get(key); + if (!Strings.isNullOrEmpty(value)) { + settings.add(new SystemSetting(key, value)); + } + } + + return settings; + } + + public boolean getBoolean(String key) { + return this.getBoolean(key, false); + } + + public boolean getBoolean(String key, boolean defaultValue) { + return this.settingsMap.containsKey(key) ? Boolean.parseBoolean(this.get(key)) : defaultValue; + } + + public Integer getInt(String key) { + return McNumberUtils.toInt(this.get(key), -1); + } + + public Integer getInt(String key, int defaultValue) { + return this.settingsMap.containsKey(key) ? McNumberUtils.toInt(this.get(key), -1) : defaultValue; + } + + public Long getLong(String key) { + return this.getLong(key, -1L); + } + + public Long getLong(String key, long defaultValue) { + if (this.settingsMap.containsKey(key)) { + String value = (String)this.settingsMap.get(key); + if (!Strings.isNullOrEmpty(value)) { + Long valueLong = McNumberUtils.toLong(value); + return valueLong == null ? defaultValue : valueLong; + } + } + + return defaultValue; + } + + public void reindex(String collection) { + switch (collection) { + case "deviceReport": + Long expiry = this.getLong("db.deviceReport.expireAfter", -1L); + McMongoUtils.dropIndex(this.mongoTemplate, "deviceReport", new String[]{"reportedAt"}); + McMongoUtils.createIndex(this.mongoTemplate, "deviceReport", new Document("reportedAt", 1), "reportedAt", (Boolean)null, expiry > 0L ? expiry : null); + break; + case "midmLog": + Long expiry = this.getLong("db.midmLog.expireAfter", -1L); + McMongoUtils.dropIndex(this.mongoTemplate, "midmLog", new String[]{"loggedAt"}); + McMongoUtils.createIndex(this.mongoTemplate, "midmLog", new Document("loggedAt", 1), "loggedAt", (Boolean)null, expiry > 0L ? expiry : null); + } + + } + + public String getFilesRootPath() { + String path = this.get("files.root"); + return Strings.isNullOrEmpty(path) ? this.filesRootDefault : path; + } + + public String getSyncServer() { + return this.get("db.sync.server"); + } + + public boolean syncOnStarts() { + return this.getBoolean("db.sync.onStarts"); + } + + public void setDbUpdated(long updatedAt) { + this.save("db.sync.updated", (Number)updatedAt); + } + + public long resourceDbUpdated() { + return this.getLong("db.sync.updated", -1L); + } + + public void loadSettings() { + MapUtils.populateMap(this.settingsMap, this.mongoTemplate.findAll(SystemSetting.class), SystemSetting::getKey, SystemSetting::getValue); + if (this.getBoolean("eulaEnabled") && !this.policyAgreementService.hasEula("service")) { + this.settingsMap.put("eulaEnabled", "false"); + } + + this.websocketBufferSize = this.getInt("websocket.buffer_size", 16) * 1024; + this.startedFrom(); + this.cloudStorageService.refresh(); + } +} diff --git a/src/main/java/com/midm/service/template/TemplateService.java b/src/main/java/com/midm/service/template/TemplateService.java new file mode 100644 index 0000000..c0bb797 --- /dev/null +++ b/src/main/java/com/midm/service/template/TemplateService.java @@ -0,0 +1,46 @@ +package com.midm.service.template; + +import com.google.common.base.Strings; +import com.midm.model.template.MailTemplate; +import com.midm.service.BaseService; +import com.midm.service.file.FileService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Lazy; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +@Service +public class TemplateService extends BaseService { + @Autowired + @Lazy + @Qualifier("fileService") + private FileService fileService; + + public MailTemplate save(MailTemplate template) { + if (template != null && !Strings.isNullOrEmpty(template.getIdName())) { + if (template.getCreated() == null) { + template.init(); + } + + this.mongoTemplate.save(template); + } + + return template; + } + + public MailTemplate find(String idName) { + return (MailTemplate)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(idName)), MailTemplate.class); + } + + public String getTemplate(String idName) { + MailTemplate template = this.find(idName); + if (template != null) { + return template.getTemplate().get("en-US").toString(); + } else { + String htmlTemplate = this.fileService.getResourceToString("mail/" + idName + ".html", false); + return !Strings.isNullOrEmpty(htmlTemplate) ? htmlTemplate : this.fileService.getResourceToString("mail/template.html", false); + } + } +} diff --git a/src/main/java/com/midm/webservice/battery/BatteryApi.java b/src/main/java/com/midm/webservice/battery/BatteryApi.java new file mode 100644 index 0000000..f8c8b14 --- /dev/null +++ b/src/main/java/com/midm/webservice/battery/BatteryApi.java @@ -0,0 +1,178 @@ +package com.midm.webservice.battery; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import com.midm.model.battery.Battery; +import com.midm.model.battery.BatteryLog; +import com.midm.model.device.Device; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.battery.BatteryService; +import com.midm.service.device.DeviceService; +import com.midm.service.org.UserService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import java.security.Principal; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/battery"}) +public class BatteryApi { + @Autowired + private BatteryService batteryService; + @Autowired + private DeviceService deviceService; + @Autowired + private UserService userService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveBattery(HttpServletRequest request, HttpServletResponse response) { + List batteries = (List)McJsonUtils.toObject(request, (new TypeToken() { + }).getType()); + if (batteries != null && !batteries.isEmpty()) { + Collection result = this.batteryService.saveBatteries(batteries); + return MidmResponse.getSucceedResponse((Object)result.size()); + } else { + return MidmResponse.getResponse(421, "No reports."); + } + } + + @RequestMapping( + value = {"/report"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String report(HttpServletRequest request, HttpServletResponse response) { + List reports = (List)McJsonUtils.toObject(request, (new TypeToken() { + }).getType()); + if (reports != null && !reports.isEmpty()) { + Collection result = this.batteryService.saveBatteryLogs(reports, "period"); + return MidmResponse.getSucceedResponse((Object)result.size()); + } else { + return MidmResponse.getResponse(421, "No reports."); + } + } + + @RequestMapping( + value = {"/setRegisterState"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String setRegisterState(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam List batteryUuids, @RequestParam String registerState) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.batteryService.setRegisterState(batteryUuids, registerState); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findBatteries(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false,defaultValue = "profile.hardware_info.batterySerial") String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(412, "No user logged in."); + } else { + String servletPath = request.getServletPath(); + loggedUser.setPageSetting(servletPath, "page", page); + loggedUser.setPageSetting(servletPath, "count", size); + if (!Strings.isNullOrEmpty(sortBy)) { + loggedUser.setPageSetting(servletPath, "sortBy", sortBy); + } + + if (direction != null) { + loggedUser.setPageSetting(servletPath, "direction", direction); + } + + if (filter != null) { + loggedUser.setPageSetting(servletPath, "filter", filter.toString()); + } + + this.userService.setSitePageSetting(loggedUser, loggedUser.getSiteUuid(), servletPath, loggedUser.getPageSettings(servletPath)); + Page pageResult = this.batteryService.findBatteries(loggedUser.getSiteUuid(), filter, page, size, sortBy, direction); + return pageResult != null && pageResult.getSize() != 0 ? MidmResponse.getSucceedResponse(pageResult) : MidmResponse.getResponse(421, "No records."); + } + } + + @RequestMapping( + value = {"/findBy"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findBatteryBy(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID batteryUuid, @RequestParam(required = false) String batterySerial) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Battery battery = null; + if (batterySerial != null) { + battery = this.batteryService.findByBatterySerial(batterySerial); + } + + return battery != null ? MidmResponse.getSucceedResponse((Object)battery) : MidmResponse.getResponse(421, "No records."); + } + } + + @RequestMapping( + value = {"/findBatteryLog"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String findBatteryLog(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestBody(required = false) DbObject settings, @RequestParam String deviceSerial, @RequestParam(name = "timeOffset",required = false) Integer minOffset) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = null; + if (!McStringUtils.isNullOrEmpty(deviceSerial)) { + device = this.deviceService.findBySerialNo(deviceSerial); + } + + if (device == null) { + return MidmResponse.getResponse(461, "No device exists."); + } else if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + DateTime from = new DateTime(McDateTimeUtils.parseDate(settings.getString("from"), (String)null)); + DateTime to = (new DateTime(McDateTimeUtils.parseDate(settings.getString("to"), (String)null))).plusDays(1); + List logs = this.batteryService.findBatteryLogByRange(deviceSerial, from.toDate(), to.toDate()); + return !logs.isEmpty() ? MidmResponse.getSucceedResponse(logs) : MidmResponse.getResponse(421, "No records."); + } + } + } +} diff --git a/src/main/java/com/midm/webservice/cloud/CloudStorageApi.java b/src/main/java/com/midm/webservice/cloud/CloudStorageApi.java new file mode 100644 index 0000000..7345fb7 --- /dev/null +++ b/src/main/java/com/midm/webservice/cloud/CloudStorageApi.java @@ -0,0 +1,128 @@ +package com.midm.webservice.cloud; + +import com.google.common.base.Strings; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.service.cloudStorage.AwsS3; +import com.midm.service.file.FileService; +import com.midm.service.org.UserService; +import com.midm.service.system.SettingsService; +import java.net.URI; +import java.util.StringJoiner; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.util.Pair; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kinesisvideo.KinesisVideoClient; +import software.amazon.awssdk.services.kinesisvideo.KinesisVideoClientBuilder; +import software.amazon.awssdk.services.kinesisvideo.model.ChannelProtocol; +import software.amazon.awssdk.services.kinesisvideo.model.ChannelRole; +import software.amazon.awssdk.services.kinesisvideo.model.GetSignalingChannelEndpointRequest; +import software.amazon.awssdk.services.kinesisvideo.model.GetSignalingChannelEndpointResponse; +import software.amazon.awssdk.services.kinesisvideo.model.ResourceEndpointListItem; +import software.amazon.awssdk.services.kinesisvideo.model.SingleMasterChannelEndpointConfiguration; +import software.amazon.awssdk.services.kinesisvideosignaling.KinesisVideoSignalingClient; +import software.amazon.awssdk.services.kinesisvideosignaling.KinesisVideoSignalingClientBuilder; +import software.amazon.awssdk.services.kinesisvideosignaling.model.GetIceServerConfigRequest; +import software.amazon.awssdk.services.kinesisvideosignaling.model.GetIceServerConfigResponse; +import software.amazon.awssdk.services.kinesisvideosignaling.model.IceServer; + +@Controller +@RequestMapping({"/api/cloud"}) +public class CloudStorageApi { + private static final String AWS_STUN = "stun:stun.kinesisvideo.%s.amazonaws.com:443"; + @Autowired + private UserService userService; + @Autowired + private FileService fileService; + @Autowired + private SettingsService settingsService; + + @RequestMapping( + value = {"/awsS3/regions"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + return MidmResponse.getSucceedResponse((Object)AwsS3.getRegions()); + } + + @RequestMapping( + value = {"/updateMetaInfo"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String updateMetaInfo(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + this.fileService.syncLocalToCloud(); + return MidmResponse.getSucceedResponse(); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/getAwsIceServer"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAwsIceServer(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + String arn = this.settingsService.get("rtc.aws.arn"); + if (Strings.isNullOrEmpty(arn)) { + return MidmResponse.getResponse(400, "Null rtc.aws.arn in SystemSetting"); + } else { + String[] element = arn.split(":"); + if (element.length < 6) { + return MidmResponse.getResponse(400, "rtc.aws.arn format is wrong, length less than 6"); + } else { + String region = element[3]; + Pair result = this.getIceList(arn, region); + return MidmResponse.getResponse((Integer)result.getFirst(), (String)result.getSecond()); + } + } + } + } + + private Pair getIceList(String arn, String region) { + try { + KinesisVideoClient kinesisVideoClient = (KinesisVideoClient)((KinesisVideoClientBuilder)((KinesisVideoClientBuilder)KinesisVideoClient.builder().credentialsProvider(InstanceProfileCredentialsProvider.create())).region(Region.of(region))).build(); + GetSignalingChannelEndpointRequest endPointRequest = (GetSignalingChannelEndpointRequest)GetSignalingChannelEndpointRequest.builder().channelARN(arn).singleMasterChannelEndpointConfiguration((SingleMasterChannelEndpointConfiguration)SingleMasterChannelEndpointConfiguration.builder().protocols(new ChannelProtocol[]{ChannelProtocol.HTTPS, ChannelProtocol.WSS}).role(ChannelRole.VIEWER).build()).build(); + GetSignalingChannelEndpointResponse endPointResponse = kinesisVideoClient.getSignalingChannelEndpoint(endPointRequest); + if (endPointResponse.resourceEndpointList().isEmpty()) { + return Pair.of(400, "Can't get any SignalingChannelEndpoint for HTTPS or WSS"); + } else { + KinesisVideoSignalingClient client = (KinesisVideoSignalingClient)((KinesisVideoSignalingClientBuilder)((KinesisVideoSignalingClientBuilder)((KinesisVideoSignalingClientBuilder)KinesisVideoSignalingClient.builder().credentialsProvider(InstanceProfileCredentialsProvider.create())).endpointOverride(URI.create(((ResourceEndpointListItem)endPointResponse.resourceEndpointList().get(0)).resourceEndpoint()))).region(Region.of(region))).build(); + GetIceServerConfigRequest request = (GetIceServerConfigRequest)GetIceServerConfigRequest.builder().channelARN(arn).build(); + GetIceServerConfigResponse response = client.getIceServerConfig(request); + StringJoiner newlineJoiner = new StringJoiner("\n"); + newlineJoiner.add(String.format("stun:stun.kinesisvideo.%s.amazonaws.com:443", region)); + + for(IceServer server : response.iceServerList()) { + for(String uri : server.uris()) { + String commaJoiner = String.join(",", uri, server.username(), server.password()); + newlineJoiner.add(commaJoiner); + } + } + + return Pair.of(200, newlineJoiner.toString()); + } + } catch (Exception e) { + return Pair.of(400, e.getMessage()); + } + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceApi.java b/src/main/java/com/midm/webservice/device/DeviceApi.java new file mode 100644 index 0000000..bfa7124 --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceApi.java @@ -0,0 +1,1485 @@ +package com.midm.webservice.device; + +import com.google.common.base.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceKey; +import com.midm.model.device.DeviceLicense; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.DeviceReport; +import com.midm.model.file.OtaFile; +import com.midm.model.log.MidmLog; +import com.midm.model.message.MidmPacket; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.model.org.UserToken; +import com.midm.service.device.DeviceAppsService; +import com.midm.service.device.DeviceKeyService; +import com.midm.service.device.DeviceReportService; +import com.midm.service.device.DeviceService; +import com.midm.service.device.DevicesParser; +import com.midm.service.device.ProfileService; +import com.midm.service.file.FileService; +import com.midm.service.log.LogService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.news.NewsMessageService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.LicenseService; +import com.mitac.cell.barcode.QrCode; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.internet.http.UserAgent; +import com.mitac.cell.io.McFile; +import com.mitac.cell.io.McResource; +import com.mitac.cell.security.McBase64; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.UpdateResult; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.socket.CloseStatus; + +@Controller +@RequestMapping({"/api/device"}) +public class DeviceApi { + @Autowired + private DeviceService deviceService; + @Autowired + private DeviceReportService deviceReportService; + @Autowired + private DeviceAppsService deviceAppsService; + @Autowired + private DeviceKeyService deviceKeyService; + @Autowired + private UserService userService; + @Autowired + private HostLicenseService hostLicenseService; + @Autowired + private FileService fileService; + @Autowired + private ProfileService profileService; + @Autowired + private WebSocketSessionManager sessionManager; + @Autowired + private LogService logService; + @Autowired + private SiteService siteService; + @Autowired + private LicenseService licenseService; + @Autowired + private NewsMessageService newsMessageService; + + @RequestMapping( + value = {"/checkIn"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String checkOut(HttpServletRequest request, Locale locale, Model model) { + return null; + } + + @RequestMapping( + value = {"/checkOut"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String checkOut(HttpServletRequest request, Authentication authentication) { + SecurityContextHolder.getContext().setAuthentication((Authentication)null); + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/remoteUrl/{serialNo}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getRemoteUrl(HttpServletRequest request, @RequestHeader("Authorization") String accessToken, @PathVariable String serialNo) { + User user = this.userService.authorizedUser((Authentication)null, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findBySerialNo(serialNo); + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + UserToken deviceToken = new UserToken(user, 'D', 3600000L); + deviceToken.setReference("deviceUuid", device.getUuid()); + this.userService.save(deviceToken); + return MidmResponse.getSucceedResponse((Object)deviceToken.toDeviceAccess(request)); + } + } + } + + @RequestMapping( + value = {"/save", "/register"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID licenseModelUuid, @RequestParam(required = false,defaultValue = "false") boolean autoRenew, @RequestParam(required = false,defaultValue = "false") boolean renewToSameModel) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site; + if (siteUuid != null) { + site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } + + if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(433, String.format("%s is not belonged to the site.", user.getEmail())); + } + } else if (!Strings.isNullOrEmpty(siteId)) { + site = this.siteService.findByIdName(siteId); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } + + siteUuid = site.getUuid(); + if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(433, String.format("%s is not belonged to the site.", user.getEmail())); + } + } else { + siteUuid = user.getSiteUuid(); + if (siteUuid == null) { + return MidmResponse.getResponse(433, String.format("%s is not belonged to any site.", user.getEmail())); + } + + site = this.siteService.findByUuid(siteUuid); + } + + JsonElement jBody = McJsonUtils.toJsonElement(request); + if (jBody == null) { + return MidmResponse.getResponse(463, "No device deifned."); + } else { + List devices = null; + if (jBody.isJsonObject()) { + Device device = (Device)McJsonUtils.toObject(jBody, Device.class); + devices = Arrays.asList(device); + } else if (jBody.isJsonArray()) { + devices = (List)McJsonUtils.toObject(jBody, (new TypeToken() { + }).getType()); + } + + if (devices != null && !devices.isEmpty()) { + for(Device device : devices) { + if (device != null) { + if (device.getSiteUuid() == null) { + device.setSiteUuid(siteUuid); + } else if (!user.isBelongedToSite(device.getSiteUuid())) { + return MidmResponse.getResponse(433, String.format("%s is not belonged to the device site.", user.getEmail())); + } + + int result = this.upsertDevice(user, device, licenseModelUuid, autoRenew, renewToSameModel); + switch (result) { + case 416: + return MidmResponse.getResponse(result, "Device is registered already to other site."); + case 421: + return MidmResponse.getResponse(result, "Exceed device limit for the host license."); + case 422: + return MidmResponse.getResponse(result, "Device serial may not matched with existing device."); + case 433: + return MidmResponse.getResponse(result, String.format("%s is not belonged to the device site(%s).", user.getEmail(), site.getName())); + case 461: + return MidmResponse.getResponse(result, "No serial no. defined."); + default: + this.sessionManager.onDisconnected(device.getUuid(), CloseStatus.NORMAL); + } + } + } + + return MidmResponse.getSucceedResponse(); + } else { + return MidmResponse.getResponse(463, "No device deifned."); + } + } + } + } + + private int upsertDevice(User user, Device device, UUID licenseModelUuid, boolean autoRenew, boolean renewToSameModel) { + String serialNo = device.getSerialNo(); + if (!Strings.isNullOrEmpty(serialNo)) { + serialNo = serialNo.trim(); + } + + if (!Strings.isNullOrEmpty(serialNo) && serialNo.length() >= 4) { + device.setSerialNo(serialNo); + UUID deviceUuid = device.getUuid(); + if (deviceUuid == null) { + device.init(); + } + + deviceUuid = device.getUuid(); + UUID siteUuid = device.getSiteUuid(); + Device existDevice = this.deviceService.findBySerialNo(serialNo); + if (existDevice != null) { + if (!existDevice.getSiteUuid().equals(siteUuid)) { + return 416; + } + + if (!existDevice.getUuid().equals(deviceUuid)) { + device.setUuid(existDevice.getUuid()); + } + } else if (this.hostLicenseService.isExceedDeviceLimit()) { + return 421; + } + + UUID deviceGroupUuid = device.getGroupUuid(); + if (deviceGroupUuid != null) { + DeviceGroup deviceGroup = this.deviceService.findDeviceGroup(deviceGroupUuid); + if (deviceGroup != null && deviceGroup.getSiteUuid().equals(siteUuid)) { + device.setDeviceGroup(deviceGroup); + } else { + device.setDeviceGroup((DeviceGroup)null); + } + } + + if (device.getDeviceGroup() == null) { + String groupPath = device.getGroupPath(); + if (!Strings.isNullOrEmpty(groupPath)) { + DeviceGroup deviceGroup = this.deviceService.findDeviceGroup(siteUuid, groupPath, true); + device.setDeviceGroup(deviceGroup); + } + } + + User owner = null; + if (device.getOwnerUuid() != null) { + owner = this.userService.findUserByUserUuid(device.getOwnerUuid()); + } + + if (owner == null) { + owner = device.getOwner(); + if (owner != null) { + String email = owner.getEmail(); + owner = this.userService.findUserByEmail(device.getSiteUuid(), email); + device.setProfile("owner", "email", email); + } else { + String email = (String)device.getCategoryProfile("owner", "email"); + if (!Strings.isNullOrEmpty(email)) { + owner = this.userService.findUserByEmail(device.getSiteUuid(), email); + } + } + } + + if (owner != null) { + if (owner.isBelongedToSite(device.getSiteUuid())) { + device.setOwner(owner); + } else { + device.setProfile("owner", "email", owner.getEmail()); + device.setOwner((User)null); + } + } else { + device.setOwner((User)null); + } + + device.setUpdated(); + if (!this.hostLicenseService.isStandalone() && licenseModelUuid != null) { + this.deviceService.setLicense(device, licenseModelUuid, true, autoRenew, renewToSameModel); + } + + device = this.deviceService.save(device); + if (!Strings.isNullOrEmpty(device.getRsa())) { + this.deviceKeyService.save(device, device.getRsa()); + } + + this.logService.save(user, device.getUuid(), "update", "Device information has been updated, force device to reconnect"); + this.sessionManager.sendUpdateFeedback(device); + return 200; + } else { + return 461; + } + } + + @RequestMapping( + value = {"/changeOwner"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String changeOwner(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "devices") String[] deviceUuids, @RequestBody(required = false) User owner, @RequestParam(required = false) UUID ownerUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.getSiteUuid() != null && user.canHandle(user.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + List devices = this.deviceService.findDevices(user.getSiteUuid(), deviceUuids); + if (devices != null && !devices.isEmpty()) { + if (owner == null) { + if (ownerUuid != null) { + owner = this.userService.findUser(ownerUuid, (String)null); + } + + if (owner == null) { + return MidmResponse.getResponse(412, "No user exists."); + } + } + + long n = this.deviceService.updateDeviceOwner(devices, owner); + List logs = new ArrayList(); + String log = "Device owner assigned: " + owner.getEmail(); + + for(Device device : devices) { + logs.add(new MidmLog(user, device.getUuid(), "update", log)); + } + + if (!logs.isEmpty()) { + this.logService.save((Collection)logs); + } + + return MidmResponse.getSucceedResponse((Object)n); + } else { + return MidmResponse.getResponse(421, "No device exists."); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/changeGroup"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String changeDeviceGroup(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "devices") String[] deviceUuids, @RequestParam(name = "group",required = false) UUID groupUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.getSiteUuid() != null && user.canHandle(user.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + List devices = this.deviceService.findDevices(user.getSiteUuid(), deviceUuids); + if (devices != null && !devices.isEmpty()) { + DeviceGroup deviceGroup = null; + if (groupUuid != null) { + deviceGroup = this.deviceService.findDeviceGroup(groupUuid); + if (deviceGroup == null) { + return MidmResponse.getResponse(421, "No group exists."); + } + } + + long n = this.deviceService.updateDeviceGroup(devices, deviceGroup); + List logs = new ArrayList(); + String log = deviceGroup == null ? "Device group unassigned." : "Device group assigned: " + this.deviceService.getGroupPath(deviceGroup); + + for(Device device : devices) { + logs.add(new MidmLog(user, device.getUuid(), "update", log)); + } + + if (!logs.isEmpty()) { + this.logService.save((Collection)logs); + } + + return MidmResponse.getSucceedResponse((Object)n); + } else { + return MidmResponse.getResponse(421, "No device exists."); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/update/{deviceUuid}/{key}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateDeviceProfile(HttpServletRequest request, Authentication authentication, @PathVariable UUID deviceUuid, @PathVariable String key) { + Document value = (Document)McJsonUtils.toObject(request, Document.class); + UpdateResult result = this.deviceService.update(deviceUuid, key, value); + if (key.equals("profile.network.telephony")) { + key = key + " - " + value.getString("carrier"); + } + + String log = String.format("Device information(%s) has been updated.", key); + MidmLog midmLog = new MidmLog((User)null, deviceUuid, "update", log); + this.logService.save(midmLog); + return result.getModifiedCount() > 0L ? MidmResponse.getSucceedResponse() : MidmResponse.getFailedResponse(); + } + + @RequestMapping( + value = {"/upsertRsa"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upsertRsaPrivateKey(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.getSiteUuid() != null && user.canHandle(user.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + String serialNo = ""; + String rsa = ""; + DbObject params = (DbObject)McJsonUtils.toObject(request, DbObject.class); + if (params != null) { + serialNo = params.getString("serialNo"); + rsa = params.getString("rsa"); + } + + if (Strings.isNullOrEmpty(serialNo)) { + return MidmResponse.getResponse(461); + } else if (Strings.isNullOrEmpty(rsa)) { + this.deviceKeyService.delete(serialNo); + return MidmResponse.getSucceedResponse(); + } else { + DeviceKey key = this.deviceKeyService.save(serialNo, rsa); + return key != null ? MidmResponse.getSucceedResponse() : MidmResponse.getFailedResponse(); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/report"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String report(HttpServletRequest request, Authentication authentication) { + List reports = (List)McJsonUtils.toObject(request, (new TypeToken() { + }).getType()); + if (reports != null && !reports.isEmpty()) { + UUID deviceUuid = ((DeviceReport)reports.get(0)).getDeviceUuid(); + Device device = (Device)this.deviceService.findById(Device.class, deviceUuid); + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + UUID siteUuid = device.getSiteUuid(); + String serialNo = device.getSerialNo(); + if (Strings.isNullOrEmpty(serialNo)) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + List logs = new ArrayList(); + MidmPacket packet = null; + Iterator it = reports.iterator(); + + while(it.hasNext()) { + DeviceReport deviceReport = (DeviceReport)it.next(); + if (!deviceReport.hasProperties()) { + it.remove(); + } else { + deviceReport.setSerialNo(serialNo); + DbObject dbProperties = deviceReport.getProperties(); + + for(String key : dbProperties.keySet()) { + DbObject dbProperty = dbProperties.getDbObject(new String[]{key}); + if (key.equals("software_info")) { + String curSkuId = device.getSkuId(); + String displayId = dbProperties.getDbObject(new String[]{key}).getString("display_id"); + String newSkuId = OtaFile.parseSkuId(displayId); + if (curSkuId != null && !curSkuId.equals(newSkuId)) { + this.deviceService.updateProfile(deviceUuid, "hardware_info.sku_id", newSkuId); + } + + this.deviceService.updateProfile(deviceUuid, key, dbProperty); + this.deviceReportService.requestToApplyOtaFirst(device); + } else if (key.equals("deviceProfile")) { + dbProperty.convertUuid("uuid"); + this.deviceReportService.updateDeviceProfileState(deviceReport); + } else if (key.equals("app")) { + this.deviceAppsService.removeCache(deviceUuid); + String packageName = dbProperty.getString("packageName"); + String label = dbProperty.getString("label"); + String status = dbProperty.getString("status"); + String log = null; + if (status.equals("added")) { + if (!Strings.isNullOrEmpty(packageName)) { + String versionName = dbProperty.getString("versionName"); + int versionCode = dbProperty.getInteger("versionCode"); + boolean isReplaced = dbProperty.getBoolean("replaced", false); + if (versionCode > 0) { + log = String.format("App(%s %s(%d)) has been %s.", packageName, versionName, versionCode, isReplaced ? "replaced" : "added"); + this.deviceAppsService.updateDeviceAppState(deviceUuid, packageName, versionCode, versionName, label); + } else { + this.sessionManager.updateInstalledApps(deviceUuid, 5000); + log = String.format("App(%s) has been %s.", packageName, isReplaced ? "replaced" : "added"); + } + } + } else { + if (status.equals("removed")) { + this.deviceAppsService.removeDeviceApp(deviceUuid, packageName); + } + + log = String.format("App(%s) has been %s.", packageName, status); + } + + this.deviceAppsService.removeCache(deviceUuid); + MidmLog midmLog = new MidmLog((User)null, deviceUuid, "activity", log); + midmLog.addReference("app", dbProperty); + midmLog.setLoggedAt(deviceReport.getReportedAt()); + if (this.logService.exists(midmLog)) { + it.remove(); + } else { + logs.add(midmLog); + } + } else if (key.equals("data_usage")) { + this.deviceReportService.saveDataUsage(device, dbProperty); + it.remove(); + } else if (key.equals("telephony")) { + String simState = dbProperty.getString("sim_state"); + if (!Strings.isNullOrEmpty(simState)) { + this.deviceService.updateTelephony(deviceUuid, dbProperty); + String log = String.format("SIM card state: %s", simState); + MidmLog midmLog = new MidmLog((User)null, deviceUuid, "network", log); + midmLog.addReference("telephony", dbProperty); + midmLog.setLoggedAt(deviceReport.getReportedAt()); + logs.add(midmLog); + } + } else if (key.equals("storage")) { + DbObject storageInfo = dbProperties.getDbObject(new String[]{"storage"}); + String media = storageInfo.getString("media"); + String status = storageInfo.getString("status"); + String log = String.format("Media(%s) has been %s.", media, status); + MidmLog midmLog = new MidmLog((User)null, deviceUuid, "activity", log); + midmLog.setLoggedAt(deviceReport.getReportedAt()); + logs.add(midmLog); + packet = new MidmPacket(131); + packet.setRecieverUuid(deviceUuid); + MidmResponse response = new MidmResponse(131, (String)null); + response.setReference(dbProperties.getDbObject(new String[]{"storage"})); + packet.setFeedback(response); + } else if (key.equals("error")) { + this.newsMessageService.saveOrUpdateInstallError(device, dbProperty); + } + } + } + } + + if (packet != null) { + this.sessionManager.sendPacketToOnlineUsers(siteUuid, packet); + } + + if (!reports.isEmpty()) { + this.deviceReportService.save(siteUuid, reports); + } + + if (!logs.isEmpty()) { + this.logService.save((Collection)logs); + } + + return MidmResponse.getSucceedResponse((Object)reports.size()); + } + } + } else { + return MidmResponse.getResponse(421, "No reports."); + } + } + + @RequestMapping( + value = {"/location"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String location(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) String serialNo, @RequestParam(required = false) Long from, @RequestParam(required = false) Long to) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = null; + if (deviceUuid != null) { + device = (Device)this.deviceService.findById(Device.class, deviceUuid); + } + + if (device == null && !Strings.isNullOrEmpty(serialNo)) { + device = this.deviceService.findBySerialNo(serialNo); + } + + if (device == null) { + return MidmResponse.getResponse(461, "No device exists."); + } else if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + List reports = this.deviceReportService.findByDeviceUuidAndLocationExists(device.getUuid(), from, to); + return reports != null && reports.size() > 0 ? MidmResponse.getSucceedResponse(reports) : MidmResponse.getResponse(421, "No locations."); + } + } + } + + @RequestMapping( + value = {"/dataUsage"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String dataUsage(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @CookieValue(required = false) TimeZone timeZone, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) String serialNo, @RequestParam(required = false,defaultValue = "both") String networkType, @RequestParam(required = false) Date from, @RequestParam(required = false) Date to, @RequestParam(required = false) McDateTimeUtils.FREQUENCY frequency, @RequestParam(required = false,defaultValue = "false") boolean separate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = null; + if (deviceUuid != null) { + device = (Device)this.deviceService.findById(Device.class, deviceUuid); + } + + if (device == null && !Strings.isNullOrEmpty(serialNo)) { + device = this.deviceService.findBySerialNo(serialNo); + } + + if (device == null) { + return MidmResponse.getResponse(461, "No device exists."); + } else if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.deviceReportService.updateDataUsage(device, (Date)null); + if (timeZone == null) { + Site site = user.getSite(); + if (site == null) { + site = this.siteService.findByUuid(user.getSiteUuid()); + } + + timeZone = site.getTimeZone(); + } + + List dataUsage = this.deviceReportService.getDataUsage(device, from, to, frequency, networkType, timeZone, separate); + Document result = (new Document("serialNo", device.getSerialNo())).append("deviceUuid", device.getUuid()).append("from", from).append("to", to).append("frequency", frequency).append("usage", dataUsage); + return MidmResponse.getSucceedResponse((Object)result); + } + } + } + + @RequestMapping( + value = {"/latestLocation"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String latestLocation(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) String serialNo) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UUID siteUuid = this.deviceService.getSiteUuid(deviceUuid); + if (siteUuid == null && !Strings.isNullOrEmpty(serialNo)) { + siteUuid = this.deviceService.getSiteUuid(serialNo); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(461, "No device exists."); + } else if (!user.canHandle(siteUuid, UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + DeviceReport report = this.deviceReportService.findLatestLocation(deviceUuid); + return report != null ? MidmResponse.getSucceedResponse(report.getProperty("location")) : MidmResponse.getResponse(421, "No locations."); + } + } + } + + @RequestMapping( + value = {"/reports"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findReportByDeviceUuid(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) String serialNo, @RequestParam(required = false) String key, @RequestParam(required = false,defaultValue = "10") Integer limit) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = null; + if (deviceUuid != null) { + device = this.deviceService.findDeviceByUuid(deviceUuid); + } + + if (device == null && !Strings.isNullOrEmpty(serialNo)) { + device = this.deviceService.findBySerialNo(serialNo); + } + + if (device != null && user.isBelongedToSite(device.getSiteUuid())) { + List reports = this.deviceReportService.find(device.getUuid(), key, limit); + return MidmResponse.getSucceedResponse(reports); + } else { + return MidmResponse.getResponse(461, "No device exists."); + } + } + } + + @RequestMapping( + value = {"/profile/progress"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getProgress(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) String serialNo, @RequestParam(required = false) UUID profileUuid) { + Device device = deviceUuid != null ? this.deviceService.findDeviceByUuid(deviceUuid) : this.deviceService.findBySerialNo(serialNo); + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + return profileUuid != null ? MidmResponse.getSucceedResponse((Object)this.deviceReportService.profileProgress(device, profileUuid)) : MidmResponse.getSucceedResponse(this.deviceReportService.profileProgress(device)); + } + } + + @RequestMapping( + value = {"/profile/progress/{deviceUuid}/{profileUuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getProgressHtml(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable UUID deviceUuid, @PathVariable UUID profileUuid) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findDeviceByUuid(deviceUuid); + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + return !loggedUser.isBelongedToSite(device.getSiteUuid()) ? MidmResponse.getResponse(415, "Not authorized.") : this.deviceReportService.profileProgressToHtmlContent(device, profileUuid); + } + } + } + + @RequestMapping( + value = {"/findBy"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findByUuid(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID uuid, @RequestParam(required = false) String serialNo, @RequestParam(required = false,defaultValue = "false") Boolean minify) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = null; + if (uuid != null) { + device = this.deviceService.findDeviceByUuid(uuid); + } + + if (device == null && McStringUtils.isValid(serialNo)) { + device = this.deviceService.findBySerialNo(serialNo); + } + + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else if (!loggedUser.isBelongedToSite(device.getSiteUuid())) { + return MidmResponse.getResponse(421, "Device not belonged to the current site."); + } else if (!loggedUser.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + if (!minify) { + if (device.getOwner() == null) { + Object email = device.getCategoryProfile("owner", "email"); + if (email != null) { + User user = this.userService.findUserByEmail(device.getSiteUuid(), (String)email); + if (user != null) { + device.setOwner(user); + this.deviceService.save(device); + } + } + } + + if (device.getGroupUuid() != null) { + DeviceGroup deviceGroup = this.deviceService.findDeviceGroup(device.getGroupUuid()); + device.setDeviceGroup(deviceGroup); + } + + List profiles = this.profileService.profileStatesByDevice(device); + device.setDeviceProfiles(profiles); + DeviceKey key = this.deviceKeyService.findBySerialNo(device.getSerialNo()); + if (key != null) { + device.setRsa(key.getRsa()); + } + } else { + device.setLicense((DeviceLicense)null); + device.setLicensed((Date)null); + device.setLicenseExpiry((Date)null); + } + + return MidmResponse.getSucceedResponse((Object)device); + } + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) boolean deviceScope, @RequestParam(required = false,defaultValue = "profile.hardware_info.serial_no") String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false) UUID profileUuid, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size, @RequestParam(required = false,defaultValue = "false") boolean blocked, @RequestParam(value = "licenseFilter",required = false) Integer licenseFilter) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(412, "No user logged in."); + } else { + Page pageResult = this.deviceService.findDevices(loggedUser.getSiteUuid(), filter, page, size, sortBy, direction, blocked, licenseFilter); + if (pageResult != null && pageResult.getSize() != 0) { + if (profileUuid != null) { + DeviceProfile profile = this.profileService.find(profileUuid, true); + + for(Device device : pageResult.getContent()) { + boolean isApplied = this.deviceReportService.isProfileApplied(device.getUuid(), profile); + device.setState("profileApplied", isApplied); + } + } + + String servletPath = request.getServletPath(); + if (!deviceScope) { + Document pageSetting = (new Document("page", page)).append("count", size); + if (!this.hostLicenseService.isStandalone() && licenseFilter != null) { + pageSetting.append("licenseFilter", licenseFilter); + } + + if (!Strings.isNullOrEmpty(sortBy)) { + pageSetting.append("sortBy", sortBy); + } + + if (direction != null) { + pageSetting.append("direction", direction); + } + + if (filter != null) { + pageSetting.append("filter", filter.toString()); + } + + if (blocked) { + pageSetting.append("blocked", blocked); + } + + this.userService.setSitePageSetting(loggedUser, loggedUser.getSiteUuid(), servletPath, pageSetting); + } + + return MidmResponse.getSucceedResponse(pageResult); + } else { + return MidmResponse.getResponse(421, "No records."); + } + } + } + + @RequestMapping( + value = {"/count"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String count(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (user.getSiteUuid() == null) { + return MidmResponse.getFailedResponse(); + } else { + long count = this.deviceService.getDeviceCount(user.getSiteUuid()); + return MidmResponse.getSucceedResponse((Object)count); + } + } + + @RequestMapping( + value = {"/isAlive/{deviceUuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String isAlive(HttpServletRequest request, Authentication authentication, @PathVariable UUID deviceUuid) { + boolean isOnline = this.sessionManager.isOnline(deviceUuid); + return MidmResponse.getSucceedResponse((Object)isOnline); + } + + @RequestMapping( + value = {"/isAlive/{serialNo}/{androidId}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String isAlive(HttpServletRequest request, Authentication authentication, @PathVariable String serialNo, @PathVariable String androidId) { + Device device = this.deviceService.findBySerialNo(serialNo); + boolean isOnline = false; + if (device != null) { + if (isOnline) { + Object deviceAndroidId = device.getCategoryProfile("hardware_info", "android_id"); + isOnline = deviceAndroidId != null && deviceAndroidId.equals(androidId); + } + + if (isOnline) { + isOnline = this.sessionManager.isOnline(device.getUuid()); + } + } + + return MidmResponse.getResponse(200, (String)null, isOnline); + } + + @RequestMapping( + value = {"/clearNotExisting"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String clearNotExistingGroup(HttpServletRequest request, Authentication authentication) { + int count = this.deviceService.clearGroupIfNotExists(); + return MidmResponse.getSucceedResponse((Object)count); + } + + @RequestMapping( + value = {"/enableByGroup"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String enabledDisabledByGroup(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) boolean enabled, @RequestParam(required = false) String filter) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.deviceService.enableDevicesByGroup(filter, enabled); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/enable"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String enabledDisabledBySingle(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) boolean enabled, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false,name = "uuid") List uuids, @RequestBody(required = false) List devices) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List logs = new ArrayList(); + if (deviceUuid != null) { + this.deviceService.enableDevice(deviceUuid, enabled); + logs.add(new MidmLog(loggedUser, deviceUuid, "activity", enabled ? "Enabled" : "Disabled")); + } else if (uuids != null) { + this.deviceService.enableDevice(loggedUser.getSiteUuid(), uuids, enabled); + + for(UUID uuid : uuids) { + logs.add(new MidmLog(loggedUser, uuid, "activity", enabled ? "Enabled" : "Disabled")); + } + } else if (devices != null && !devices.isEmpty()) { + this.deviceService.enableDevices(devices, enabled); + + for(Device device : devices) { + logs.add(new MidmLog(loggedUser, device.getUuid(), "activity", enabled ? "Enabled" : "Disabled")); + if (enabled) { + this.sessionManager.unblock(device.getUuid(), loggedUser); + } + } + } + + if (!logs.isEmpty()) { + this.logService.save((Collection)logs); + } + + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/unblock"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String unblock(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) String serialNo) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = null; + if (deviceUuid != null) { + device = this.deviceService.findDeviceByUuid(deviceUuid); + } + + if (device == null && McStringUtils.isValid(serialNo)) { + device = this.deviceService.findBySerialNo(serialNo); + } + + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else if (!loggedUser.isBelongedToSite(device.getSiteUuid())) { + return MidmResponse.getResponse(421, "Device not belonged to the current site."); + } else if (!loggedUser.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.sessionManager.unblock(device.getUuid(), loggedUser); + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false,name = "uuids") List ids, @RequestBody(required = false) Device device) { + if (this.hostLicenseService.getDeviceLimit() > 0) { + return MidmResponse.getResponse(421, "Not authorized."); + } else { + List uuids = null; + if (ids != null && !ids.isEmpty()) { + uuids = new ArrayList(); + + for(String id : ids) { + try { + UUID uuid = UUID.fromString(id); + uuids.add(uuid); + } catch (Exception var13) { + Device dev = this.deviceService.findBySerialNo(id); + if (dev != null) { + uuids.add(dev.getUuid()); + } + } + } + } + + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = loggedUser.getSiteUuid(); + } + + if (!loggedUser.canHandle(siteUuid, UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + int deletedCount = 0; + if (uuids != null && !uuids.isEmpty()) { + deletedCount = this.deviceService.delete(siteUuid, uuids); + } else if (device != null) { + deletedCount = this.deviceService.delete(device, false) ? 1 : 0; + } + + return MidmResponse.getSucceedResponse((Object)deletedCount); + } + } + } + } + + @RequestMapping( + value = {"/retire"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String retire(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) List uuids) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = loggedUser.getSiteUuid(); + } + + if (!loggedUser.canHandle(siteUuid, UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + return uuids != null && !uuids.isEmpty() ? MidmResponse.getSucceedResponse((Object)this.deviceService.retire(siteUuid, uuids)) : MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/exists"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String exists(HttpServletRequest request, Principal principal, @RequestParam(required = false) UUID siteUuid, @RequestParam String serialNo, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + return MidmResponse.getSucceedResponse((Object)this.deviceService.exists(siteUuid, serialNo)); + } + + @RequestMapping( + value = {"/renew"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String renew(HttpServletRequest request, Principal principal, @RequestParam(required = false) UUID siteUuid, @RequestParam String serialNo, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findBySerialNo(serialNo); + if (!loggedUser.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + if (device != null) { + this.deviceService.renewLicense(device); + } + + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/license/apply"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String applyLicense(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(value = "devices",required = false) UUID[] deviceUuids, @RequestParam(required = false) UUID licenseModelUuid, @RequestParam(required = false,defaultValue = "true") boolean keepModel, @RequestParam(required = false,defaultValue = "true") boolean autoRenew, @RequestParam(required = false,defaultValue = "true") boolean renewToSameModel) { + User user = this.userService.authorizedUser(authentication, accessToken); + UUID siteUuid = user.getSiteUuid(); + if (user != null && (user.hasRole(siteUuid, "SUPERVISOR") || user.hasRole(siteUuid, "DEVICE_MANAGER"))) { + if (deviceUuid != null) { + Device device = this.deviceService.findDeviceByUuid(deviceUuid); + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + DeviceLicense license = this.deviceService.setLicense(device, licenseModelUuid, keepModel, autoRenew, renewToSameModel); + return license != null ? MidmResponse.getSucceedResponse((Object)license) : MidmResponse.getResponse(464, "No license."); + } + } else if (deviceUuids == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + List licenes = new ArrayList(); + UUID[] license = deviceUuids; + int var15 = deviceUuids.length; + int var16 = 0; + + while(true) { + if (var16 < var15) { + UUID uuid = license[var16]; + Device device = (Device)this.deviceService.findById(Device.class, uuid); + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } + + if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } + + DeviceLicense license = this.deviceService.setLicense(device, licenseModelUuid, keepModel, autoRenew, renewToSameModel); + if (license != null) { + licenes.add(license); + ++var16; + continue; + } + } + + return MidmResponse.getSucceedResponse(); + } + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/license/remove"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String removeLicense(HttpServletRequest request, Principal principal, @RequestParam UUID deviceUuid, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findDeviceByUuid(deviceUuid); + if (device == null) { + return MidmResponse.getResponse(463, "Device is not exist."); + } else if (!loggedUser.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + DeviceLicense license = device.getLicense(); + if (license == null) { + return MidmResponse.getResponse(464, "No license."); + } else { + this.deviceService.removeLicense(device); + return MidmResponse.getSucceedResponse((Object)license); + } + } + } + } + + @RequestMapping( + value = {"/license/transfer"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String transferLicense(HttpServletRequest request, Principal principal, @RequestParam UUID deviceUuid, @RequestParam String serialNo, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findDeviceByUuid(deviceUuid); + if (device == null) { + return MidmResponse.getResponse(463, "Device is not exist."); + } else if (!loggedUser.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Device receiver = this.deviceService.findBySerialNo(serialNo); + if (receiver == null) { + return MidmResponse.getResponse(463, "Target device is not exist."); + } else { + DeviceLicense license = this.deviceService.transferLicense(device, receiver); + return license != null ? MidmResponse.getSucceedResponse((Object)license) : MidmResponse.getFailedResponse(); + } + } + } + } + + @RequestMapping( + value = {"/canTransfer"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String canTransfer(HttpServletRequest request, Principal principal, @RequestParam UUID siteUuid, @RequestParam String serialNo, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findBySerialNo(serialNo); + Site site = this.siteService.findByUuid(siteUuid); + if (!loggedUser.canHandle(siteUuid, UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + boolean canTransfer = device != null && (!device.hasLicense() || device.getLicense().isTrial() || device.isLicenseExpired()) && site != null && device.getSiteUuid().equals(siteUuid); + return MidmResponse.getSucceedResponse((Object)canTransfer); + } + } + } + + @RequestMapping( + value = {"/license/reset"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String resetLicense(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, Principal principal, @RequestParam String serialNo) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (!user.isSystemAdmin()) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findBySerialNo(serialNo); + if (device == null) { + return MidmResponse.getResponse(463, "Device not found:" + serialNo); + } else { + DeviceLicense license = this.deviceService.resetLicenses(device); + return MidmResponse.getSucceedResponse((Object)license); + } + } + } + + @RequestMapping( + value = {"/license/extend"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String reactivate(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, Principal principal, @RequestParam(required = false) String serialNo, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) UUID licenseUuid) { + Device device = null; + DeviceLicense license = null; + if (!Strings.isNullOrEmpty(serialNo)) { + device = this.deviceService.findBySerialNo(serialNo); + } else if (deviceUuid != null) { + device = this.deviceService.findDeviceByUuid(deviceUuid); + } else if (licenseUuid != null) { + license = (DeviceLicense)this.deviceService.findById(DeviceLicense.class, licenseUuid); + } + + if (device != null) { + license = device.getLicense(); + } else if (license != null) { + deviceUuid = license.getDeviceUuid(); + if (deviceUuid != null) { + device = this.deviceService.findDeviceByUuid(deviceUuid); + } + } + + if (license == null) { + return MidmResponse.getResponse(464, "No license."); + } else if (!license.canExtend()) { + return MidmResponse.getResponse(400, "License is not perpetual or not expired."); + } else if (license.reactivate()) { + Date expiry = license.getExpiry(); + if (device != null) { + this.deviceService.updateLicenseExpiry(device, expiry); + User user = this.userService.authorizedUser(authentication, accessToken); + DeviceService var10000 = this.deviceService; + String var10005 = user.getEmail(); + var10000.addLicenseLog(license, device, (Device)null, "reactivated", "License extended by " + var10005 + ", extension count = " + license.getReactivated().size()); + } + + if (license != null) { + this.deviceService.updateLicenseExpiry(license, expiry, license.getReactivated()); + } + + return MidmResponse.getSucceedResponse((Object)license); + } else { + return MidmResponse.getResponse(400, "License is not perpetual or exceed reactivation count."); + } + } + + @RequestMapping( + value = {"/enroll/qr"}, + method = {RequestMethod.GET} + ) + public void qrCode(HttpServletResponse response, @RequestParam String params) { + String ecrypted = this.deviceService.encrypt(McBase64.fromBase64ToString(params)); + byte[] bytes = McStringUtils.toBytes(ecrypted); + + try { + McResource.copyToResponse(response, QrCode.toImage(new String(bytes, "ISO-8859-1"), 200, 0)); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + } + + @RequestMapping( + value = {"/qrTemplate"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String qrRegister(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String code, @RequestParam(required = false,defaultValue = "false") boolean print) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + return loggedUser == null ? MidmResponse.getResponse(415, "Not authorized.") : this.deviceService.qrTemplate(loggedUser, code, print); + } + + @RequestMapping( + value = {"/group"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findGroup(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, Principal principal, @RequestParam String path) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceGroup group = this.deviceService.findDeviceGroup(user.getSiteUuid(), path, false); + return group != null ? MidmResponse.getSucceedResponse((Object)group) : MidmResponse.getFailedResponse(); + } + } + + @RequestMapping( + value = {"/profiles"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String profiles(HttpServletRequest request, HttpServletResponse response, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestHeader(value = "User-Agent",defaultValue = "") UserAgent userAgent, @RequestParam UUID deviceUuid, @RequestParam(required = false,defaultValue = "-1") long clientVersion, @RequestParam(required = false,defaultValue = "false") boolean withRef, @RequestParam(required = false,defaultValue = "false") boolean minify) throws IOException { + Device device = this.deviceService.findDeviceByUuid(deviceUuid); + if (device != null && (!device.isMobileConnected() || !this.deviceService.hasRoamingProblem(clientVersion))) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + if (!userAgent.isDevice() || !this.deviceService.isAuthorized(device)) { + response.sendError(401); + return null; + } + } else if (!user.canHandle(device.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + response.sendError(401); + return null; + } + + if (clientVersion > -1L) { + device.setClientVersion((int)clientVersion); + } + + List profiles = this.profileService.findAllByDevice(device, withRef, minify, true); + if (clientVersion < 0L) { + try { + for(DeviceProfile profile : profiles) { + this.profileService.notifyUpdateAfter(device.getUuid(), profile.getUuid(), 60); + } + } catch (Exception var17) { + } + } + + return profiles == null ? MidmResponse.getResponse(421, "No records.") : MidmResponse.getSucceedResponse(profiles); + } else { + return MidmResponse.getResponse(463, "No device exists."); + } + } + + @RequestMapping( + value = {"upload/screen"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String uploadScreen(HttpServletRequest request, Authentication authentication, @RequestParam UUID siteUuid, @RequestParam UUID deviceUuid, @RequestParam MultipartFile file) { + file.getOriginalFilename(); + String deviceFilePath = this.fileService.getDeviceFilePath(siteUuid, deviceUuid, "screen", "screen.png"); + McFile destFile = new McFile(deviceFilePath); + destFile.getParentFile().mkdirs(); + + try { + destFile.write(file.getInputStream()); + return MidmResponse.getSucceedResponse(); + } catch (IOException e) { + e.printStackTrace(); + return MidmResponse.getResponse(432, e.getMessage()); + } + } + + @RequestMapping( + value = {"upload/file"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String uploadFile(HttpServletRequest request, Authentication authentication, @RequestParam UUID siteUuid, @RequestParam UUID deviceUuid, @RequestParam MultipartFile file) { + UUID deviceSiteUuid = this.deviceService.getSiteUuid(deviceUuid); + if (deviceSiteUuid != null && siteUuid.equals(deviceSiteUuid)) { + String deviceFilePath = this.fileService.getDeviceFilePath(siteUuid, deviceUuid, "file", file.getOriginalFilename()); + McFile destFile = new McFile(deviceFilePath); + destFile.getParentFile().mkdirs(); + + try { + destFile.write(file.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"upload/list"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String uploadDeviceList(HttpServletRequest request, Authentication authentication, @RequestParam("file") MultipartFile file, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + return user == null ? MidmResponse.getResponse(415, "Not authorized.") : (new DevicesParser(this.hostLicenseService.isStandalone(), user.getSiteUuid(), this.userService, this.deviceService, this.licenseService)).parse(file); + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceAppApi.java b/src/main/java/com/midm/webservice/device/DeviceAppApi.java new file mode 100644 index 0000000..19d5724 --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceAppApi.java @@ -0,0 +1,219 @@ +package com.midm.webservice.device; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceApps; +import com.midm.model.file.AppFile; +import com.midm.model.message.MIDM_REQUEST; +import com.midm.model.message.MidmPacket; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.security.UserPrincipal; +import com.midm.service.device.DeviceAppsService; +import com.midm.service.device.DeviceService; +import com.midm.service.file.FileService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.UserService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/device/app"}) +public class DeviceAppApi { + @Autowired + private UserService userService; + @Autowired + private FileService fileService; + @Autowired + private DeviceService deviceService; + @Autowired + private DeviceAppsService deviceAppsService; + @Autowired + private WebSocketSessionManager websocketSessionManager; + + @RequestMapping( + value = {"install"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String install(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestParam UUID deviceUuid, @RequestParam long lastModified) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getFailedResponse(); + } else { + String originalFileName = file.getOriginalFilename(); + if (!originalFileName.endsWith(".apk")) { + return null; + } else { + UUID fileUuid = UUID.randomUUID(); + String filePath = this.fileService.getUserFilePath(user.getUuid(), fileUuid); + McFile targetFile = new McFile(filePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + targetFile.getParentFile().mkdirs(); + + try { + if (targetFile.write(file.getInputStream())) { + AppFile app = new AppFile(user, fileUuid, targetFile, false); + app.setFileName(originalFileName); + app.minify(); + MidmPacket packet = new MidmPacket(MIDM_REQUEST.COMMAND); + packet.getQuery().setSenderUuid(user.getUuid()); + packet.setRecieverUuid(deviceUuid); + packet.getQuery().setRequest("apps"); + packet.setParam("command", "install"); + String url = "userfile/" + user.getUuid() + "/" + fileUuid + "/" + originalFileName; + JsonObject jParams = new JsonObject(); + jParams.addProperty("url", url); + jParams.addProperty("remove_after_install", true); + McJsonUtils.setProperty(jParams, "data", app); + packet.setParam("params", jParams); + this.websocketSessionManager.sendMessage(packet); + return MidmResponse.getSucceedResponse((Object)app); + } else { + return MidmResponse.getFailedResponse(); + } + } catch (IOException e) { + e.printStackTrace(); + return MidmResponse.getFailedResponse(); + } + } + } + } + + @RequestMapping( + value = {"remove/userfile/{userUuid}/{fileUuid}/{fileName}", "forgetNetwork/userfile/{userUuid}/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + @ResponseBody + public String remove(HttpServletRequest request, Authentication authentication, @PathVariable UUID userUuid, @PathVariable UUID fileUuid, @PathVariable String fileName) { + String filePath = this.fileService.getUserFilePath(userUuid, fileUuid); + (new McFile(filePath)).delete(); + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"installed"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getInstalled(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) UUID uuid, @RequestParam(required = false) String serialNo) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (deviceUuid == null) { + deviceUuid = uuid; + } + + if (deviceUuid == null && Strings.isNullOrEmpty(serialNo)) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + Device device = (Device)this.deviceService.findById(Device.class, deviceUuid); + if (device == null) { + device = this.deviceService.findBySerialNo(serialNo); + } + + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else if (!user.isBelongedToSite(device.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } else { + deviceUuid = device.getUuid(); + DeviceApps apps = this.deviceAppsService.getInstalledApps(deviceUuid); + if (apps == null) { + apps = new DeviceApps(); + } + + apps.setSerialNo(device.getSerialNo()); + return MidmResponse.getSucceedResponse((Object)apps); + } + } + } + } + + @RequestMapping( + value = {"isInstalled"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String isInstalled(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false) UUID uuid, @RequestParam(required = false) String serialNo, String packageName, @RequestParam(required = false,defaultValue = "-1") int versionCode, @RequestParam(required = false) String versionName, @RequestParam(required = false,defaultValue = "-1") int minSdk) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (deviceUuid == null) { + deviceUuid = uuid; + } + + if (deviceUuid == null && Strings.isNullOrEmpty(serialNo)) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + Device device = null; + if (deviceUuid != null) { + device = (Device)this.deviceService.findById(Device.class, deviceUuid); + if (device != null) { + serialNo = device.getSerialNo(); + } + } + + if (deviceUuid == null) { + device = this.deviceService.findBySerialNo(serialNo); + } + + if (device == null) { + return MidmResponse.getResponse(463, "No device exists."); + } else { + Document result = this.deviceAppsService.installedApp(device, packageName, versionCode, versionName, minSdk); + result.append("serialNo", serialNo); + return MidmResponse.getSucceedResponse((Object)result); + } + } + } + } + + @RequestMapping( + value = {"clients"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getClients(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + return MidmResponse.getSucceedResponse(this.deviceService.getClients()); + } + + @RequestMapping( + value = {"installed/update"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateInstalled(HttpServletRequest request, Authentication authentication) { + DeviceApps apps = (DeviceApps)McJsonUtils.toObject(request, DeviceApps.class); + if (apps != null) { + apps = this.deviceAppsService.save(apps); + } + + return apps != null ? MidmResponse.getSucceedResponse() : MidmResponse.getFailedResponse(); + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceFilesApi.java b/src/main/java/com/midm/webservice/device/DeviceFilesApi.java new file mode 100644 index 0000000..3203cd0 --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceFilesApi.java @@ -0,0 +1,152 @@ +package com.midm.webservice.device; + +import com.google.gson.JsonObject; +import com.midm.model.file.BaseFile; +import com.midm.model.message.MIDM_REQUEST; +import com.midm.model.message.MidmPacket; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.SiteFile; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.security.UserPrincipal; +import com.midm.service.file.DeviceFilesService; +import com.midm.service.file.FileService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.UserService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/device/files"}) +public class DeviceFilesApi { + @Autowired + private FileService fileService; + @Autowired + private UserService userService; + @Autowired + private DeviceFilesService deviceFilesService; + @Autowired + private WebSocketSessionManager websocketSessionManager; + + @RequestMapping( + value = {"push"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String push(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestParam UUID deviceUuid, @RequestParam(required = false) long lastModified, @RequestParam String path, @RequestParam boolean extract) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getFailedResponse(); + } else { + String originalFileName = file.getOriginalFilename(); + UUID fileUuid = UUID.randomUUID(); + String filePath = this.fileService.getUserFilePath(user.getUuid(), fileUuid); + McFile targetFile = new McFile(filePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + targetFile.getParentFile().mkdirs(); + + try { + if (targetFile.write(file.getInputStream())) { + BaseFile baseFile = new BaseFile(user, fileUuid, targetFile); + baseFile.setSiteUuid(user.getSiteUuid()); + baseFile.setFileName(originalFileName); + baseFile.setLastModified(lastModified); + MidmPacket packet = new MidmPacket(MIDM_REQUEST.COMMAND); + packet.getQuery().setSenderUuid(user.getUuid()); + packet.setRecieverUuid(deviceUuid); + packet.getQuery().setRequest("files"); + packet.setParam("command", "push"); + String url = "/userfile/" + user.getUuid() + "/" + fileUuid + "/" + originalFileName; + JsonObject jParams = new JsonObject(); + jParams.addProperty("url", url); + jParams.addProperty("path", path); + jParams.addProperty("extract", extract); + packet.setParam("params", jParams); + this.websocketSessionManager.sendMessage(packet); + return MidmResponse.getSucceedResponse((Object)baseFile); + } else { + return MidmResponse.getFailedResponse(); + } + } catch (IOException e) { + e.printStackTrace(); + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (size == null) { + size = Integer.MAX_VALUE; + } + + Page pageResult = this.deviceFilesService.findDeviceFiles(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/findone"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findone(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(412, "No user logged in."); + } else { + SiteFile siteFile = this.deviceFilesService.findDeviceFileByUuid(fileUuid); + return !user.canHandle(siteFile.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES) ? MidmResponse.getResponse(433, "No permission.") : MidmResponse.getSucceedResponse((Object)siteFile); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + SiteFile siteFile = (SiteFile)McJsonUtils.toObject(request, SiteFile.class); + if (!user.canHandle(siteFile.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.deviceFilesService.delete(user.getSiteUuid(), siteFile); + return MidmResponse.getSucceedResponse((Object)siteFile); + } + } + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceGroupApi.java b/src/main/java/com/midm/webservice/device/DeviceGroupApi.java new file mode 100644 index 0000000..9411eaf --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceGroupApi.java @@ -0,0 +1,120 @@ +package com.midm.webservice.device; + +import com.midm.model.device.DeviceGroup; +import com.midm.model.log.MidmLog; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.device.DeviceService; +import com.midm.service.log.LogService; +import com.midm.service.org.UserService; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import java.security.Principal; +import java.util.Date; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/device/group"}) +public class DeviceGroupApi { + @Autowired + private DeviceService deviceService; + @Autowired + private UserService userService; + @Autowired + private LogService logService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (user.getSiteUuid() == null) { + return MidmResponse.getFailedResponse(); + } else { + DeviceGroup group = (DeviceGroup)McJsonUtils.toObject(request, DeviceGroup.class); + if (group != null && !McStringUtils.isNullOrEmpty(group.getName())) { + if (group.getUuid() == null) { + group.init(); + } + + group.setSiteUuid(user.getSiteUuid()); + group.setUpdated(new Date()); + group = this.deviceService.save(group); + MidmLog addLog = new MidmLog(); + addLog.setCategory("event"); + addLog.setForWhat(group.getUuid()); + addLog.setLog("update"); + addLog.setLogger(user); + addLog.addReference("device_group_name", group.getName()); + addLog.addReference("parentUuid", group.getParentUuid()); + this.logService.save(addLog); + return MidmResponse.getSucceedResponse((Object)group); + } else { + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/all"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,defaultValue = "true") boolean count) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (user.getSiteUuid() == null) { + return MidmResponse.getFailedResponse(); + } else { + List deviceGroups = this.deviceService.findAllDeviceGroups(user.getSiteUuid(), count); + return MidmResponse.getSucceedResponse(deviceGroups); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceGroup deviceGroup = (DeviceGroup)McJsonUtils.toObject(request, DeviceGroup.class); + DeviceGroup existGroup = this.deviceService.findDeviceGroup(deviceGroup.getUuid()); + if (existGroup == null) { + return MidmResponse.getResponse(404, "DeviceGroup not found"); + } else if (!user.canHandle(deviceGroup.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + MidmLog addLog = new MidmLog(); + addLog.setCategory("event"); + addLog.setForWhat(deviceGroup.getUuid()); + addLog.setLog("delete"); + addLog.addReference("device_group_name", deviceGroup.getName()); + this.logService.save(addLog); + this.deviceService.delete(deviceGroup); + return MidmResponse.getSucceedResponse((Object)deviceGroup); + } + } + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceLicenseApi.java b/src/main/java/com/midm/webservice/device/DeviceLicenseApi.java new file mode 100644 index 0000000..3159ec0 --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceLicenseApi.java @@ -0,0 +1,78 @@ +package com.midm.webservice.device; + +import com.google.gson.JsonObject; +import com.midm.model.device.DeviceLicense; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.service.device.DeviceService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.LicenseService; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/device/licenses"}) +public class DeviceLicenseApi { + @Autowired + private DeviceService deviceService; + @Autowired + private UserService userService; + @Autowired + private SiteService siteService; + @Autowired + private LicenseService licenseService; + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(value = "model",required = false) UUID modelUuid, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String plan, @RequestParam(required = false,defaultValue = "false") boolean licensed, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "DESC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size, @RequestParam(value = "licenseFilter",required = false) Integer licenseFilter) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = user.getSite(); + if (site == null) { + site = this.siteService.findByUuid(user.getSiteUuid()); + user.setSite(site); + } + + LicenseModel licenseModel = modelUuid == null ? null : this.licenseService.findLicenseModelByUuid(modelUuid); + Page licenses = this.deviceService.findLicenses(site, licenseModel, plan, licensed, filter, page, size, sortBy, direction, licenseFilter); + return MidmResponse.getSucceedResponse(licenses); + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String log(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, HttpServletResponse response) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List licenses = this.deviceService.findAllLicenses(user.getSite()); + return MidmResponse.getSucceedResponse(licenses); + } + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceNoteApi.java b/src/main/java/com/midm/webservice/device/DeviceNoteApi.java new file mode 100644 index 0000000..27935a2 --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceNoteApi.java @@ -0,0 +1,87 @@ +package com.midm.webservice.device; + +import com.midm.model.device.DeviceNote; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.service.device.DeviceService; +import com.midm.service.org.UserService; +import com.mitac.cell.utils.McJsonUtils; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/device/note"}) +public class DeviceNoteApi { + @Autowired + private DeviceService deviceService; + @Autowired + private UserService userService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceNote note = (DeviceNote)McJsonUtils.toObject(request, DeviceNote.class); + if (note == null) { + return MidmResponse.getFailedResponse(); + } else { + if (note.getUuid() == null) { + note.init(); + note.setWriterUuid(user.getUuid()); + } + + this.deviceService.save(note); + return MidmResponse.getSucceedResponse((Object)note); + } + } + } + + @RequestMapping( + value = {"/recent"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findByUuid(HttpServletRequest request, Authentication authentication, @RequestParam UUID deviceUuid, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List notes = this.deviceService.getRecentNotes(deviceUuid); + return MidmResponse.getSucceedResponse(notes); + } + } + + @RequestMapping( + value = {"/list"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestParam UUID deviceUuid, @RequestParam(required = false,defaultValue = "0") Integer pageNum, @RequestParam(required = true,defaultValue = "5") Integer size, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Page notes = this.deviceService.getNotes(deviceUuid, pageNum, size); + return MidmResponse.getSucceedResponse(notes); + } + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceProfileApi.java b/src/main/java/com/midm/webservice/device/DeviceProfileApi.java new file mode 100644 index 0000000..66211e3 --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceProfileApi.java @@ -0,0 +1,1049 @@ +package com.midm.webservice.device; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceProfile; +import com.midm.model.device.DeviceProfileGroup; +import com.midm.model.device.ProfileScope; +import com.midm.model.file.AppFile; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.ScheduledTaskService; +import com.midm.service.device.DeviceService; +import com.midm.service.device.MustProfileService; +import com.midm.service.device.ProfileAdvisor; +import com.midm.service.device.ProfileService; +import com.midm.service.file.FileService; +import com.midm.service.log.LogService; +import com.midm.service.org.UserService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mongodb.client.result.UpdateResult; +import java.io.IOException; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.FileUtils; +import org.bson.Document; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.HandlerMapping; + +@Controller +@RequestMapping({"/api/device/profile"}) +public class DeviceProfileApi { + @Autowired + private ProfileService profileService; + @Autowired + private ProfileAdvisor profileAdvisor; + @Autowired + private DeviceService deviceService; + @Autowired + private MustProfileService mustProfileService; + @Autowired + private FileService fileService; + @Autowired + private LogService logService; + @Autowired + private UserService userService; + @Autowired + private ScheduledTaskService scheduledTaskService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = (DeviceProfile)McJsonUtils.toObject(request, DeviceProfile.class); + if (profile == null) { + return MidmResponse.getFailedResponse(); + } else if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + profile.initApps(); + boolean isNew = false; + if (profile.getUuid() == null) { + profile.init(); + profile.setWriterUuid(user.getUuid()); + profile.setWriter(user); + profile.setProfile("applyWhile", "sleeping", true); + profile.setProfile("name", this.profileService.getNewName(user.getSiteUuid(), profile.getProfile("name").toString())); + isNew = true; + } else { + profile.setUpdated(); + } + + if (profile.getGroupUuid() != null) { + DeviceProfileGroup group = this.profileService.findDeviceProfileGroup(profile.getGroupUuid()); + if (group != null && (profile.getDeviceProfileGroup() == null || !profile.getDeviceProfileGroup().getUuid().equals(group.getUuid()))) { + profile.setDeviceProfileGroup(group); + } + } + + Object startsOnDate = profile.getProfile("startsOn"); + if (startsOnDate == null) { + profile.setProfile("startsOn", McDateTimeUtils.toString(new DateTime(profile.getUpdated()), "yyyy-MM-dd")); + } + + profile = this.profileService.save(profile); + if (!isNew) { + this.profileService.deleteProfileStateByProfile(profile.getUuid()); + } + + this.logService.save(user, profile.getUuid(), "update", isNew ? "Generated" : "Updated"); + this.scheduledTaskService.scheduleToUpdateProfile(profile); + return MidmResponse.getSucceedResponse((Object)profile); + } + } + } + + @RequestMapping( + value = {"/enable"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String enabledDisabledProfiles(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) boolean enabled, @RequestParam(name = "uuid") List uuids) { + User loggeduser = this.userService.authorizedUser(authentication, accessToken); + if (loggeduser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.profileService.enable(loggeduser.getSiteUuid(), uuids, enabled); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/sequence/set"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String setSequence(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "sequence") List uuids, @RequestParam(name = "rmSequence",defaultValue = "") List rmUuids) { + User loggeduser = this.userService.authorizedUser(authentication, accessToken); + if (loggeduser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (!rmUuids.isEmpty()) { + this.profileService.removeSequence(rmUuids); + } + + UpdateResult result = uuids.size() == 1 ? this.profileService.unsetSequence((UUID)uuids.get(0)) : this.profileService.setSequence(uuids); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"/sequence/unset"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String unsetSequence(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "sequence") UUID uuid) { + User loggeduser = this.userService.authorizedUser(authentication, accessToken); + if (loggeduser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UpdateResult result = this.profileService.unsetSequence(uuid); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"must/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String mustModelUpdate(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = (DeviceProfile)McJsonUtils.toObject(request, DeviceProfile.class); + if (profile == null) { + return MidmResponse.getFailedResponse(); + } else if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String copyFilePath = null; + boolean copyFolder = profile.getProfile("copy") != null; + if (copyFolder) { + copyFilePath = this.fileService.getMustFolderRootPath(user.getSiteUuid(), profile.getUuid()); + profile.setUuid((UUID)null); + } + + if (profile.getUuid() == null) { + profile.init(); + profile.setWriterUuid(user.getUuid()); + profile.setWriter(user); + String filePath = this.fileService.getMustFolderRootPath(user.getSiteUuid(), profile.getUuid()); + if (copyFolder) { + McFile copyFile = new McFile(copyFilePath); + McFile targetFile = new McFile(filePath); + if (copyFile.exists()) { + try { + FileUtils.copyDirectory(copyFile, targetFile); + } catch (IOException var14) { + } + } + } else if (!(new McFile(filePath)).exists()) { + String[] subFolders = new String[]{"app", "apps", "files/client", "/files/manufacturer", "/media", "/META-INF/com/android", "/must", "/Pic/Kernel", "/Pic/UT", "/Pic/wallpaper"}; + + for(String subFolder : subFolders) { + (new McFile(filePath, subFolder)).mkdirs(); + } + } + + profile.setProfile("copy", (Object)null); + } else { + profile.setUpdated(); + } + + if (profile.getGroupUuid() != null) { + DeviceProfileGroup group = this.profileService.findDeviceProfileGroup(profile.getGroupUuid()); + if (group != null && (profile.getDeviceProfileGroup() == null || !profile.getDeviceProfileGroup().getUuid().equals(group.getUuid()))) { + profile.setDeviceProfileGroup(group); + } + } + + profile = this.profileService.save(profile); + return MidmResponse.getSucceedResponse((Object)profile); + } + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + String servletPath = request.getServletPath(); + loggedUser.setPageSetting(servletPath, "page", page); + loggedUser.setPageSetting(servletPath, "count", size); + if (!Strings.isNullOrEmpty(sortBy)) { + loggedUser.setPageSetting(servletPath, "sortBy", sortBy); + } + + if (direction != null) { + loggedUser.setPageSetting(servletPath, "direction", direction); + } + + if (filter != null) { + loggedUser.setPageSetting(servletPath, "filter", filter.toString()); + } + + this.userService.setSitePageSetting(loggedUser, loggedUser.getSiteUuid(), servletPath, loggedUser.getPageSettings(servletPath)); + Page pageResult = this.profileService.findProfiles(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/devices"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findDevices(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID profileUuid, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false,defaultValue = "profile.hardware_info.serial_no") String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Page pageResult = this.profileService.findDevices(profileUuid, filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/all"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(value = "siteUuid",required = true) UUID siteUuid) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List profiles = this.profileService.findAllBySiteUuid(siteUuid); + return MidmResponse.getSucceedResponse(profiles); + } + } + + @RequestMapping( + value = {"/{profileUuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, HttpServletResponse response, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable UUID profileUuid, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false,defaultValue = "false") boolean withRef, @RequestParam(required = false,defaultValue = "-1") long clientVersion, @RequestParam(required = false,defaultValue = "-1") long updated, @RequestParam(required = false,defaultValue = "false") boolean minify) { + if (deviceUuid != null) { + Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid); + if (device != null && device.isMobileConnected() && this.deviceService.hasRoamingProblem(clientVersion)) { + return MidmResponse.getFailedResponse(); + } + } + + DeviceProfile profile = this.profileService.findByDeviceAndProfile(deviceUuid, profileUuid, withRef, minify); + if (profile == null) { + return MidmResponse.getResponse(421, "No profile found or unavailable(disabled/ended)."); + } else if (profile.getUpdated().getTime() == updated) { + try { + response.sendError(204); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } else { + if (clientVersion > 0L && this.deviceService.hasDateTimeProblem(clientVersion)) { + profile.unsetDateTimeSettings(); + } + + return MidmResponse.getSucceedResponse((Object)profile); + } + } + + @RequestMapping( + value = {"{modelSite}/{profileUuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findModelProfile(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String modelSite, @PathVariable UUID profileUuid, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false,defaultValue = "false") Boolean minify) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (deviceUuid == null) { + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } + + user.getSiteUuid(); + } + + DeviceProfile profile = this.profileService.findByDeviceAndProfile(deviceUuid, profileUuid, false, minify); + if (profile == null) { + return MidmResponse.getResponse(421, "No profile found."); + } else { + return !user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES) ? MidmResponse.getResponse(433, "No permission.") : MidmResponse.getSucceedResponse((Object)profile); + } + } + + @RequestMapping( + value = {"{modelSite}/{profileUuid}/**"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getPath(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String modelSite, @PathVariable UUID profileUuid, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false,defaultValue = "false") Boolean minify) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = this.profileService.find(profileUuid, true); + if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String path = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); + String[] tempPath = path.split("/", 7); + List pathObject = this.fileService.getFileList(user.getSiteUuid(), profileUuid, tempPath[6]); + return pathObject == null ? MidmResponse.getResponse(421, "No Folder found") : MidmResponse.getSucceedResponse(pathObject); + } + } + } + + @RequestMapping( + value = {"/addFolder/{modelSite}/{profileUuid}/**"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String addFolder(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String newFolder, @PathVariable String modelSite, @PathVariable UUID profileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = this.profileService.find(profileUuid, true); + if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + if (newFolder == null) { + newFolder = "newFolder"; + } + + String path = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); + String[] tempPath = path.split("/", 8); + this.fileService.addFolder(user.getSiteUuid(), profileUuid, tempPath[7], newFolder); + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/deleteFiles/{modelSite}/{profileUuid}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteFiles(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String filePath, @RequestParam(required = false) UUID fileUuid, @PathVariable String modelSite, @PathVariable UUID profileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = this.profileService.find(profileUuid, true); + if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.fileService.deleteFiles(user.getSiteUuid(), profileUuid, filePath); + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"{modelSite}/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false) Long lastModified, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String currentPath, @RequestParam(required = false) UUID profileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = this.profileService.find(profileUuid, true); + if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String originalFileName = file.getOriginalFilename(); + if (lastModified == null) { + lastModified = (new Date()).getTime(); + } + + AppFile app = null; + String category = "others"; + if (currentPath.equalsIgnoreCase("root")) { + currentPath = ""; + } else if (currentPath.startsWith("apps")) { + category = "apps"; + } + + String filePath = this.fileService.getMustFolderFilePath(user.getSiteUuid(), profileUuid, currentPath + "/" + originalFileName); + McFile targetFile = new McFile(filePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + try { + targetFile.write(file.getInputStream()); + if (category.equals("apps")) { + app = new AppFile(user, fileUuid, targetFile); + if (app.getAppInfo().isEmpty()) { + targetFile.delete(); + return MidmResponse.getResponse(400, "Not apk file."); + } else { + (new McFile(targetFile.getPath() + ".png")).delete(); + app.setName(originalFileName); + return MidmResponse.getSucceedResponse((Object)app); + } + } else { + return MidmResponse.getSucceedResponse((Object)targetFile); + } + } catch (IOException e) { + return MidmResponse.getResponse(400, e.getMessage()); + } + } + } + } + + @RequestMapping( + value = {"/b2c"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findByModel(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, Principal principal) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = this.profileService.findOne(user); + return MidmResponse.getSucceedResponse((Object)profile); + } + } + + @RequestMapping( + value = {"/applyByDevice"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String applyByDevice(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID uuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Device device = this.deviceService.findOnlineDeviceFirst(uuid); + if (device == null) { + return MidmResponse.getFailedResponse(); + } else if (!user.canHandle(device.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else if (this.profileService.notifyUpdate(device)) { + this.logService.save(user, device.getUuid(), "activity", "Notified to apply"); + return MidmResponse.getSucceedResponse(); + } else { + this.logService.save(user, device.getUuid(), "activity", "Failed to notify to apply"); + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/apply"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String apply(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID profileUuid, @RequestBody(required = false) DeviceProfile deviceProfile) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } + + DeviceProfile orgProfile = null; + if (profileUuid != null) { + orgProfile = this.profileService.find(profileUuid, false); + if (orgProfile != null) { + if (user.isBelongedToSite(orgProfile.getSiteUuid())) { + Document result = this.notifyToApply(user, orgProfile); + return MidmResponse.getSucceedResponse((Object)result); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } else { + return MidmResponse.getResponse(421, "No profile found."); + } + } else if (deviceProfile == null) { + return MidmResponse.getResponse(421, "No profile found."); + } else { + boolean needToSave = false; + if (deviceProfile.getUuid() != null) { + orgProfile = this.profileService.find(deviceProfile.getUuid(), false); + } + + if (orgProfile != null) { + if (!siteUuid.equals(orgProfile.getSiteUuid())) { + return MidmResponse.getResponse(415, "Not authorized."); + } + + if (!orgProfile.getUpdated().equals(deviceProfile.getUpdated())) { + deviceProfile.setUuid(orgProfile.getUuid()); + deviceProfile.setCreated(orgProfile.getCreated()); + deviceProfile.setUpdated(); + deviceProfile.setSiteUuid(siteUuid); + deviceProfile.setEnabled(true); + if (Strings.isNullOrEmpty(deviceProfile.getName())) { + String profileName = orgProfile.getName(); + if (Strings.isNullOrEmpty(profileName)) { + profileName = McDateTimeUtils.toString(deviceProfile.getCreated(), user.getSite().getTimeZone(), "yyyyMMdd-hhmmss"); + } + + deviceProfile.setName(profileName); + } + + this.updateScopedDevices(deviceProfile); + Set prevDevices = orgProfile.getScopedDevice(); + if (prevDevices != null && !prevDevices.isEmpty()) { + Set curDevices = deviceProfile.getScopedDevice(); + if (curDevices != null && !curDevices.isEmpty()) { + Iterator itDevices = prevDevices.iterator(); + + while(itDevices.hasNext()) { + if (curDevices.contains(itDevices.next())) { + itDevices.remove(); + } + } + } + + this.profileService.notifyDevicesToRemoveProfile(prevDevices, profileUuid); + } + + needToSave = true; + } + } else { + if (deviceProfile.getUuid() == null) { + deviceProfile.generateId(); + } + + deviceProfile.setEnabled(true); + deviceProfile.setSiteUuid(siteUuid); + Date now = new Date(); + if (deviceProfile.getCreated() == null) { + deviceProfile.setCreated(now); + } + + if (deviceProfile.getUpdated() == null) { + deviceProfile.setUpdated(now); + } + + if (Strings.isNullOrEmpty(deviceProfile.getName())) { + deviceProfile.setName(McDateTimeUtils.toString(new DateTime(deviceProfile.getCreated()), "yyyyMMdd-hhmmss")); + } + + this.updateScopedDevices(deviceProfile); + needToSave = true; + } + + if (!user.canHandle(deviceProfile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + if (needToSave) { + deviceProfile = this.profileService.save(deviceProfile); + } + + Document result = this.notifyToApply(user, deviceProfile); + return MidmResponse.getSucceedResponse((Object)result); + } + } + } + } + + private Document notifyToApply(User user, DeviceProfile deviceProfile) { + this.scheduledTaskService.cancelSchedule(deviceProfile.getUuid()); + if (this.profileService.notifyUpdate(deviceProfile, true)) { + this.logService.save(user, deviceProfile.getUuid(), "activity", "Notified to apply"); + } else { + this.logService.save(user, deviceProfile.getUuid(), "activity", "Failed to notify or no device to notify to apply."); + } + + return (new Document("uuid", deviceProfile.getUuid())).append("name", deviceProfile.getName()).append("updated", deviceProfile.getUpdated().getTime()); + } + + private void updateScopedDevices(DeviceProfile deviceProfile) { + if (deviceProfile.isGlobal()) { + deviceProfile.setScope((ProfileScope)null); + } else { + UUID siteUuid = deviceProfile.getSiteUuid(); + Set devices = deviceProfile.getScopedDevice(); + if (devices != null && !devices.isEmpty()) { + List serials = new ArrayList(); + Iterator it = devices.iterator(); + + while(true) { + String deviceId; + Device device; + while(true) { + if (!it.hasNext()) { + if (!serials.isEmpty()) { + devices.addAll(serials); + } + + return; + } + + deviceId = (String)it.next(); + device = null; + if (deviceId.length() != 36) { + break; + } + + try { + UUID deviceUuid = UUID.fromString(deviceId); + device = (Device)this.deviceService.findById(Device.class, deviceUuid); + if (device == null) { + break; + } + + if (device.getSiteUuid().equals(siteUuid)) { + serials.add(device.getSerialNo()); + break; + } + } catch (Exception var9) { + break; + } + } + + if (device == null) { + device = this.deviceService.findBySerialNo(deviceId); + if (device == null) { + device = new Device(); + device.init(); + device.setSiteUuid(siteUuid); + device.setSerialNo(deviceId); + device.setEnabled(true); + this.deviceService.save(device); + serials.add(deviceId); + } else if (device.getSiteUuid().equals(siteUuid)) { + serials.add(deviceId); + } + } + } + } + } + } + + @RequestMapping( + value = {"/applyAll"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String applyAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestBody DeviceProfile profile) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (profile == null) { + return MidmResponse.getFailedResponse(); + } else if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.scheduledTaskService.cancelSchedule(profile.getUuid()); + profile.convertCustomSettingsForDevice(); + if (this.profileService.notifyUpdateAll(profile)) { + this.logService.save(user, profile.getUuid(), "activity", "Notified to apply"); + return MidmResponse.getSucceedResponse(); + } else { + this.logService.save(user, profile.getUuid(), "activity", "Failed to notify to apply"); + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/sync"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deviceGroupRemoved(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam("profile") UUID profileUuid, @RequestParam("group") UUID groupUuid, @RequestParam("status") int code) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile deviceProfile = this.profileService.find(profileUuid, false); + if (deviceProfile == null) { + return MidmResponse.getFailedResponse(); + } else if (user != null && !user.isBelongedToSite(deviceProfile.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String command = null; + switch (code) { + case 136: + command = "remove_profile"; + default: + for(Device device : this.deviceService.findAllDevicesInGroup(groupUuid, (JsonObject)null)) { + this.profileService.notifyToSync(device, profileUuid, command, code); + } + + return MidmResponse.getSucceedResponse(); + } + } + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "uuid",required = false) List uuids) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List profiles = this.profileService.findByIds(DeviceProfile.class, uuids); + List removed = new ArrayList(); + + for(DeviceProfile deviceProfile : profiles) { + if (user == null || user.isBelongedToSite(deviceProfile.getSiteUuid())) { + this.profileService.delete(deviceProfile); + removed.add(deviceProfile.getUuid()); + this.profileService.notifyDevicesToRemoveProfile(this.profileService.getScopedDevices(deviceProfile), deviceProfile.getUuid()); + } + } + + if (removed.isEmpty()) { + return MidmResponse.getResponse(421, "No profile found."); + } else { + return MidmResponse.getSucceedResponse(removed); + } + } + } + + @RequestMapping( + value = {"must/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String mustProfileDelete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile deviceProfile = (DeviceProfile)McJsonUtils.toObject(request, DeviceProfile.class); + if (user != null && !user.isBelongedToSite(deviceProfile.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } else if (!this.profileService.exists(deviceProfile)) { + return MidmResponse.getResponse(421, "No profile found."); + } else { + this.profileService.delete(deviceProfile); + String filePath = this.fileService.getMustFolderRootPath(deviceProfile.getSiteUuid(), deviceProfile.getUuid()); + (new McFile(filePath)).delete(); + return MidmResponse.getSucceedResponse((Object)deviceProfile); + } + } + } + + @RequestMapping( + value = {"must/generate"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String generateFile(HttpServletRequest request, HttpServletResponse response, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile deviceProfile = (DeviceProfile)McJsonUtils.toObject(request, DeviceProfile.class); + if (user != null && !user.isBelongedToSite(deviceProfile.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } else if (!this.profileService.exists(deviceProfile)) { + return MidmResponse.getResponse(421, "No profile found."); + } else { + this.mustProfileService.build(deviceProfile); + return MidmResponse.getSucceedResponse((Object)deviceProfile); + } + } + } + + @RequestMapping( + value = {"must/download"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String downloadFile(HttpServletRequest request, HttpServletResponse response, Principal principal, @RequestParam(required = false) String file, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) UUID fileUuid) { + JsonObject jFile = McJsonUtils.toJsonElement(file).getAsJsonObject(); + boolean isDirectory = Boolean.valueOf(jFile.get("isDirectory").toString()); + String path = jFile.get("path").getAsString(); + String folderName = jFile.get("name").getAsString(); + String root = this.fileService.getMustFolderRootPath(siteUuid, fileUuid); + String targetPath = this.fileService.getMustFolderFilePath(siteUuid, fileUuid, path); + if (isDirectory) { + this.mustProfileService.compressSingleFolder(fileUuid, root, targetPath, "tempDownlad", folderName); + } + + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/{profileUuid}/scope/{command}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateScope(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable UUID profileUuid, @PathVariable String command, @RequestParam(required = false,defaultValue = "false") boolean registerIfNotExists, @RequestParam(name = "device",required = false,defaultValue = "") Set devices, @RequestParam(name = "group",required = false,defaultValue = "") Set groups) { + if (!command.equals("add") && !command.equals("remove")) { + return MidmResponse.getResponse(422, "Unknown command. only allowed to be 'add | remove'."); + } else { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = (DeviceProfile)this.profileService.findById(DeviceProfile.class, profileUuid); + if (profile == null) { + return MidmResponse.getResponse(421, "No profile found or unavailable(disabled/ended)."); + } else if (!user.isBelongedToSite(profile.getSiteUuid())) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UUID siterUuid = profile.getSiteUuid(); + Set existingDevices = new HashSet(); + devices.forEach((serialNo) -> { + Device device = this.deviceService.findBySerialNo(serialNo); + if (device == null) { + try { + UUID deviceUuid = UUID.fromString(serialNo); + device = this.deviceService.findDeviceByUuid(deviceUuid); + } catch (Exception var8) { + } + } + + if (device != null) { + if (device.getSiteUuid().equals(siterUuid)) { + existingDevices.add(device.getSerialNo()); + } + } else if (command.equals("add") && registerIfNotExists) { + device = new Device(); + device.init(); + device.setSiteUuid(siterUuid); + device.setSerialNo(serialNo); + device.setEnabled(true); + this.deviceService.save(device); + } + + }); + Set existingGroups = new HashSet(); + groups.forEach((group) -> { + DeviceGroup deviceGroup = null; + + try { + UUID groupUuid = UUID.fromString(group); + deviceGroup = (DeviceGroup)this.deviceService.findById(DeviceGroup.class, groupUuid); + } catch (Exception var6) { + deviceGroup = this.deviceService.findDeviceGroup(profile.getSiteUuid(), group, false); + } + + if (deviceGroup != null && deviceGroup.getSiteUuid().equals(profile.getSiteUuid())) { + existingGroups.add(deviceGroup.getUuid()); + } + + }); + if (existingDevices.isEmpty() && existingGroups.isEmpty()) { + return MidmResponse.getResponse(421, "No devices or groups is defined."); + } else { + boolean updated = this.profileService.updateScope(profile, command, existingDevices, existingGroups); + if (updated) { + this.logService.save(user, profile.getUuid(), "activity", "Scope " + (command.equals("add") ? "added" : "removed")); + } + + return MidmResponse.getSucceedResponse((Object)updated); + } + } + } + } + } + + @RequestMapping( + value = {"/count"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String count(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (user.getSiteUuid() == null) { + return MidmResponse.getFailedResponse(); + } else { + long count = this.profileService.getProfileCount(user.getSiteUuid()); + return MidmResponse.getSucceedResponse((Object)count); + } + } + + @RequestMapping( + value = {"/advice"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String advice(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "uuid") UUID uuid) { + Document conflicts = this.profileAdvisor.advice(uuid); + return MidmResponse.getSucceedResponse((Object)conflicts); + } + + @RequestMapping( + value = {"/import"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String uploadProfile(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam MultipartFile file, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) UUID groupUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfile profile = new DeviceProfile(); + + try { + profile = (DeviceProfile)McJsonUtils.toObject(file.getInputStream(), DeviceProfile.class); + } catch (IOException var11) { + } + + if (profile != null) { + boolean isNew = false; + if (profile.getUuid() == null) { + profile.init(); + profile.setWriterUuid(user.getUuid()); + profile.setWriter(user); + isNew = true; + } else { + profile.setUpdated(); + } + + profile.setSiteUuid(siteUuid); + if (groupUuid != null) { + DeviceProfileGroup group = (DeviceProfileGroup)this.profileService.findById(DeviceProfileGroup.class, groupUuid); + if (group != null) { + profile.setDeviceProfileGroup(group); + } + } + + profile.setProfile("name", this.profileService.getNewName(siteUuid, profile.getProfile("name").toString())); + Object startsOnDate = profile.getProfile("startsOn"); + if (startsOnDate == null) { + profile.setProfile("startsOn", (new DateTime(profile.getUpdated())).toLocalDate().toDate()); + } + + if (!user.canHandle(profile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + profile = this.profileService.save(profile); + this.logService.save(user, profile.getUuid(), "update", isNew ? "Generated" : "Updated"); + if (!isNew) { + this.scheduledTaskService.scheduleToUpdateProfile(profile); + } + + return MidmResponse.getSucceedResponse((Object)profile); + } + } else { + return MidmResponse.getFailedResponse(); + } + } + } +} diff --git a/src/main/java/com/midm/webservice/device/DeviceProfileGroupApi.java b/src/main/java/com/midm/webservice/device/DeviceProfileGroupApi.java new file mode 100644 index 0000000..1a834eb --- /dev/null +++ b/src/main/java/com/midm/webservice/device/DeviceProfileGroupApi.java @@ -0,0 +1,119 @@ +package com.midm.webservice.device; + +import com.midm.model.device.DeviceProfileGroup; +import com.midm.model.log.MidmLog; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.device.ProfileService; +import com.midm.service.log.LogService; +import com.midm.service.org.UserService; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import java.security.Principal; +import java.util.Date; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/device/profile/group"}) +public class DeviceProfileGroupApi { + @Autowired + private ProfileService profileService; + @Autowired + private UserService userService; + @Autowired + private LogService logService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (user.getSiteUuid() == null) { + return MidmResponse.getFailedResponse(); + } else { + DeviceProfileGroup group = (DeviceProfileGroup)McJsonUtils.toObject(request, DeviceProfileGroup.class); + if (group != null && !McStringUtils.isNullOrEmpty(group.getName())) { + if (group.getUuid() == null) { + group.init(); + } + + group.setSiteUuid(user.getSiteUuid()); + group.setUpdated(new Date()); + group = this.profileService.save(group); + MidmLog addLog = new MidmLog(); + addLog.setCategory("event"); + addLog.setForWhat(group.getUuid()); + addLog.setLog("update"); + addLog.setLogger(user); + addLog.addReference("profile_group_name", group.getName()); + addLog.addReference("parentUuid", group.getParentUuid()); + this.logService.save(addLog); + return MidmResponse.getSucceedResponse((Object)group); + } else { + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/all"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (user.getSiteUuid() == null) { + return MidmResponse.getFailedResponse(); + } else { + List deviceProfileGroups = this.profileService.findAllDeviceProfileGroups(user.getSiteUuid()); + return MidmResponse.getSucceedResponse(deviceProfileGroups); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + DeviceProfileGroup deviceProfileGroup = (DeviceProfileGroup)McJsonUtils.toObject(request, DeviceProfileGroup.class); + DeviceProfileGroup existGroup = this.profileService.findDeviceProfileGroup(deviceProfileGroup.getUuid()); + if (existGroup == null) { + return MidmResponse.getResponse(404, "Profile group not found."); + } else if (!user.canHandle(deviceProfileGroup.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + MidmLog addLog = new MidmLog(); + addLog.setCategory("event"); + addLog.setForWhat(deviceProfileGroup.getUuid()); + addLog.setLog("delete"); + addLog.addReference("profile_group_name", deviceProfileGroup.getName()); + this.logService.save(addLog); + this.profileService.delete(deviceProfileGroup); + return MidmResponse.getSucceedResponse((Object)deviceProfileGroup); + } + } + } +} diff --git a/src/main/java/com/midm/webservice/files/AppsApi.java b/src/main/java/com/midm/webservice/files/AppsApi.java new file mode 100644 index 0000000..0a04359 --- /dev/null +++ b/src/main/java/com/midm/webservice/files/AppsApi.java @@ -0,0 +1,449 @@ +package com.midm.webservice.files; + +import com.google.common.base.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.model.device.DeviceProfile; +import com.midm.model.file.AppFile; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.ProfileService; +import com.midm.service.file.FileService; +import com.midm.service.org.UserService; +import com.mitac.cell.internet.http.McHttpClient; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McUrlUtils; +import com.mongodb.client.result.UpdateResult; +import java.io.File; +import java.io.FilenameFilter; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/apps"}) +public class AppsApi { + @Autowired + private FileService fileService; + @Autowired + private ProfileService profileService; + @Autowired + private UserService userService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (filter == null) { + filter = new JsonObject(); + } + + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(415, "User is not belonged to the site."); + } else { + if (!filter.has("siteUuid")) { + filter.addProperty("siteUuid", siteUuid.toString()); + } + + Page pageResult = this.fileService.findApps(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(415, "User is not belonged to the site."); + } else { + List apps = this.fileService.findApps(siteUuid, filter, sortBy, direction); + return MidmResponse.getSucceedResponse(apps); + } + } + } + + @RequestMapping( + value = {"/profiles/{uuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String deviceProfiles(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable UUID uuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List profiles = this.profileService.findAllByApp(uuid); + return MidmResponse.getSucceedResponse(profiles); + } + } + + @RequestMapping( + value = {"/info/{uuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String info(HttpServletRequest request, Authentication authentication, @PathVariable UUID uuid, @RequestParam(required = false,defaultValue = "-1") long versionCode, @RequestParam(required = false,defaultValue = "false") Boolean minify) { + AppFile app = this.fileService.findApp(uuid, minify); + if (app == null) { + JsonObject jData = new JsonObject(); + jData.addProperty("exists", false); + MidmResponse response = new MidmResponse(400, "failed", jData); + return response.toString(); + } else { + return app.getVersionCode() == versionCode ? MidmResponse.getSucceedResponse((Object)"Not modified.") : MidmResponse.getSucceedResponse((Object)app); + } + } + + @RequestMapping( + value = {"/info"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String info(HttpServletRequest request, Authentication authentication, @RequestParam List uuids, @RequestParam(required = false) List expiries, @RequestParam(required = false) List checksums, @RequestParam(required = false,defaultValue = "false") Boolean minify) { + Map results = new HashMap(); + + for(int i = 0; i < uuids.size(); ++i) { + UUID uuid = (UUID)uuids.get(i); + long expiry = expiries != null ? (Long)expiries.get(i) : -1L; + long checksum = checksums != null ? (Long)checksums.get(i) : -1L; + AppFile app = this.fileService.findApp(uuid, minify); + if (app == null) { + results.put(uuid, new Document("exists", false)); + } else if (app.getChecksum() == checksum && expiries != null && expiry == app.getUrlExpiry()) { + results.put(uuid, new Document("isSame", "true")); + } else { + results.put(uuid, app); + } + } + + return MidmResponse.getSucceedResponse((Object)results); + } + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + AppFile app = (AppFile)McJsonUtils.toObject(request, AppFile.class); + if (!user.canHandle(app.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.fileService.save(app); + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/updateExtras"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateExtras(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!this.fileService.existsById(AppFile.class, uuid)) { + return MidmResponse.getResponse(421, "No apps found."); + } else { + UpdateResult result = this.fileService.updateExtras(AppFile.class, uuid, request.getParameterMap()); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"/rename"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String rename(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID fileUuid, @RequestParam String name) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.fileService.rename(fileUuid, name, AppFile.class); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/nameExists"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String nameExists(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String name) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean exists = this.fileService.nameExists(user.getSiteUuid(), (UUID)null, name, AppFile.class); + return MidmResponse.getSucceedResponse((Object)exists); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + AppFile[] apps = (AppFile[])McJsonUtils.toObject(request, AppFile[].class); + if (apps != null && apps.length != 0) { + this.fileService.delete(user.getSiteUuid(), apps); + return MidmResponse.getSucceedResponse((Object)apps); + } else { + return MidmResponse.getResponse(421, "No apps found."); + } + } + } + + @RequestMapping( + value = {"/addLink"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String addLink(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false) URL url, @RequestParam(required = false) Boolean keepInHost, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + AppFile appFile = null; + if (fileUuid == null) { + notifyToUpdate = false; + } else { + appFile = this.fileService.findApp(fileUuid, true); + if (appFile != null && !user.isBelongedToSite(appFile.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } + } + + JsonElement jReference = McJsonUtils.toJsonElement(request); + JsonObject reference = jReference == null ? new JsonObject() : jReference.getAsJsonObject(); + if (url == null) { + String link = reference.get("url").getAsString(); + url = McUrlUtils.toUrl(link); + } + + HttpURLConnection conn = McHttpClient.open(url); + if (conn == null) { + return MidmResponse.getResponse(432, "The given link is not able to connect."); + } else { + String originalFileName = McHttpClient.getFileName(conn); + String contentType = conn.getContentType(); + if ((Strings.isNullOrEmpty(originalFileName) || !originalFileName.endsWith(".apk")) && !Strings.isNullOrEmpty(contentType) && !contentType.startsWith("application/vnd.android.package-archive") && contentType.equals("application/octet-stream")) { + conn.disconnect(); + return MidmResponse.getResponse(400, "The given link seems invalid Android app."); + } else { + if (keepInHost == null) { + keepInHost = McJsonUtils.getBoolean(reference, "keepInHost", false); + } + + try { + String result = this.writeFile(user, appFile, conn.getInputStream(), originalFileName, conn.getLastModified(), keepInHost ? null : url.toString(), notifyToUpdate, request.getParameterMap()); + conn.disconnect(); + return result; + } catch (Exception var16) { + conn.disconnect(); + return MidmResponse.getResponse(432, "Failed to save the file."); + } + } + } + } + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam MultipartFile file, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false,defaultValue = "0") long lastModified, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!file.getContentType().startsWith("application/vnd.android.package-archive") && file.getContentType().equals("application/octet-stream") && !file.getOriginalFilename().endsWith("apk")) { + return MidmResponse.getResponse(400, "Not apk file."); + } else { + String originalFileName = file.getOriginalFilename(); + AppFile appFile = null; + if (fileUuid != null) { + appFile = this.fileService.findApp(fileUuid, false); + if (appFile != null && !user.isBelongedToSite(appFile.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } + } + + try { + return this.writeFile(user, appFile, file.getInputStream(), originalFileName, lastModified, (String)null, notifyToUpdate, request.getParameterMap()); + } catch (Exception e) { + String var10001 = e.getMessage(); + return MidmResponse.getResponse(400, var10001 + " -> " + originalFileName); + } + } + } + + private String writeFile(User user, AppFile orgAppFile, InputStream input, String fileName, long lastModified, String url, boolean notifyToUpdate, Map params) { + UUID fileUuid = UUID.randomUUID(); + String filePath = this.fileService.getFilePath(user.getSiteUuid(), "app", fileUuid); + McFile targetFile = new McFile(filePath); + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + if (targetFile.write(input)) { + AppFile newAppFile = new AppFile(user, fileUuid, targetFile); + newAppFile.setExtra(params); + boolean keepInHost = Strings.isNullOrEmpty(url); + if (newAppFile.getAppInfo().isEmpty()) { + targetFile.delete(); + return MidmResponse.getResponse(400, "Not apk file."); + } else { + newAppFile.setFileName(fileName); + if (orgAppFile != null) { + fileUuid = orgAppFile.getFileUuid(); + if (!newAppFile.getPackageName().equals(orgAppFile.getPackageName())) { + this.deleteApp(targetFile); + return MidmResponse.getResponse(400, "Diffrent package name."); + } + + newAppFile.setFileUuid(fileUuid); + newAppFile.setName(orgAppFile.getName()); + String orgFilePath = this.fileService.getFilePath(user.getSiteUuid(), "app", fileUuid); + McFile iconFile = new McFile(targetFile.getPath() + ".png"); + McFile orgFile = new McFile(orgFilePath); + orgFile.delete(); + targetFile.renameTo(orgFile); + iconFile.renameTo(new McFile(orgFile.getPath() + ".png")); + targetFile = orgFile; + } else { + newAppFile.setName(this.findName(user.getSiteUuid(), fileUuid, newAppFile.getLabel())); + } + + newAppFile.setSiteUuid(user.getSiteUuid()); + if (!keepInHost) { + newAppFile.setFileUrl(url); + targetFile.delete(); + } + + newAppFile.setLastModified(lastModified); + this.fileService.save(newAppFile); + if (this.cloudStorageService.hasCloudStorage()) { + this.cloudStorageService.upload(targetFile, fileName, targetFile.getContentType(), user.getSiteUuid(), "app", fileUuid); + McFile iconFile = new McFile(targetFile.getPath() + ".png"); + this.cloudStorageService.upload(iconFile, (new McFile(fileName)).getNameWithoutExtension() + ".png", iconFile.getContentType(), user.getSiteUuid(), "app", fileUuid + ".png"); + } + + if (notifyToUpdate) { + this.notifyUpdate(newAppFile.getFileUuid(), notifyToUpdate); + } + + return MidmResponse.getSucceedResponse((Object)newAppFile); + } + } else { + return MidmResponse.getResponse(400, "Write failed : " + targetFile.getPath()); + } + } + + private String findName(UUID siteUuid, UUID fileUuid, String label) { + String name = label; + + for(int i = 1; this.fileService.nameExists(siteUuid, fileUuid, name, AppFile.class); name = String.format("%s (%d)", label, i++)) { + } + + return name; + } + + private void deleteApp(McFile appFile) { + McFile parentFile = appFile.getParentFile(); + FilenameFilter filenameFilter = (dir, name) -> name.startsWith(appFile.getName()); + File[] files = parentFile.listFiles(filenameFilter); + + for(File file : files) { + file.delete(); + } + + } + + private void notifyUpdate(UUID uuid, Boolean notifyToUpdate) { + List profiles = this.profileService.findAllByApp(uuid); + if (profiles != null && !profiles.isEmpty()) { + for(DeviceProfile profile : profiles) { + profile.setUpdated(); + this.profileService.save(profile); + if (notifyToUpdate && profile.getEnabled()) { + this.profileService.notifyUpdate(profile, false); + } + } + + } + } +} diff --git a/src/main/java/com/midm/webservice/files/FilesApi.java b/src/main/java/com/midm/webservice/files/FilesApi.java new file mode 100644 index 0000000..fe134f7 --- /dev/null +++ b/src/main/java/com/midm/webservice/files/FilesApi.java @@ -0,0 +1,399 @@ +package com.midm.webservice.files; + +import com.google.api.client.util.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.model.device.DeviceProfile; +import com.midm.model.file.BaseFile; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.ProfileService; +import com.midm.service.file.FileService; +import com.midm.service.org.UserService; +import com.mitac.cell.internet.http.McHttpClient; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McUrlUtils; +import com.mongodb.client.result.UpdateResult; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/files"}) +public class FilesApi { + @Autowired + private FileService fileService; + @Autowired + private ProfileService profileService; + @Autowired + private UserService userService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (filter == null) { + filter = new JsonObject(); + } + + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(415, "User is not belonged to the site."); + } else { + if (!filter.has("siteUuid")) { + filter.addProperty("siteUuid", siteUuid.toString()); + } + + Page pageResult = this.fileService.findFiles(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(415, "User is not belonged to the site."); + } else { + List files = this.fileService.findFiles(siteUuid, filter, sortBy, direction); + return MidmResponse.getSucceedResponse(files); + } + } + } + + @RequestMapping( + value = {"/info/{uuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String info(HttpServletRequest request, Authentication authentication, @PathVariable UUID uuid, @RequestParam(required = false,defaultValue = "-1") long checksum, @RequestParam(required = false,defaultValue = "0") long expiry, @RequestParam(required = false,defaultValue = "true") boolean minify) { + BaseFile file = this.fileService.findFile(uuid); + if (file == null) { + JsonObject jData = new JsonObject(); + jData.addProperty("exists", false); + MidmResponse response = new MidmResponse(400, "failed", jData); + return response.toString(); + } else { + if (minify) { + file.minify(); + } + + return checksum > 0L && file.getChecksum() == checksum && expiry == file.getUrlExpiry() ? MidmResponse.getSucceedResponse() : MidmResponse.getSucceedResponse((Object)file); + } + } + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + BaseFile file = (BaseFile)McJsonUtils.toObject(request, BaseFile.class); + if (!user.canHandle(file.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.fileService.save(file); + return MidmResponse.getSucceedResponse((Object)file); + } + } + } + + @RequestMapping( + value = {"/updateExtras"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateExtras(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!this.fileService.existsById(BaseFile.class, uuid)) { + return MidmResponse.getResponse(421, "No apps found."); + } else { + UpdateResult result = this.fileService.updateExtras(BaseFile.class, uuid, request.getParameterMap()); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + BaseFile baseFile = (BaseFile)McJsonUtils.toObject(request, BaseFile.class); + if (!user.canHandle(baseFile.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.fileService.delete(user.getSiteUuid(), baseFile); + return MidmResponse.getSucceedResponse((Object)baseFile); + } + } + } + + @RequestMapping( + value = {"/sync"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String clear(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + return user != null && user.hasSystemRole("SYSTEM_ADMIN") ? MidmResponse.getSucceedResponse((Object)this.fileService.sync()) : MidmResponse.getResponse(415, "Not authorized."); + } + + @RequestMapping( + value = {"/rename"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String rename(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID fileUuid, @RequestParam String name) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.fileService.rename(fileUuid, name, BaseFile.class); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/nameExists"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String nameExists(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String name) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean exists = this.fileService.nameExists(user.getSiteUuid(), (UUID)null, name, BaseFile.class); + return MidmResponse.getSucceedResponse((Object)exists); + } + } + + @RequestMapping( + value = {"/addLink"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String addLink(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false) URL url, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + JsonObject reference = McJsonUtils.toJsonElement(request).getAsJsonObject(); + String link = reference.get("url").getAsString(); + boolean keepInHost = McJsonUtils.getBoolean(reference, "keepInHost", false); + if (url == null) { + url = McUrlUtils.toUrl(link); + } + + HttpURLConnection conn = McHttpClient.open(url); + if (conn == null) { + return MidmResponse.getResponse(432, "The given link is not able to connect."); + } else { + String name = null; + if (fileUuid == null) { + fileUuid = UUID.randomUUID(); + notifyToUpdate = false; + } else { + BaseFile baseFile = this.fileService.findFile(fileUuid); + if (baseFile != null) { + name = baseFile.getName(); + } + } + + String filePath = this.fileService.getFilePath(user.getSiteUuid(), "other", fileUuid); + McFile targetFile = new McFile(filePath); + + String var16; + try { + String originalFileName = McHttpClient.getFileName(conn); + var16 = this.writeFile(user, fileUuid, conn.getInputStream(), targetFile, originalFileName, name, conn.getContentType().split(";")[0], conn.getLastModified(), keepInHost ? null : link, notifyToUpdate, request.getParameterMap()); + return var16; + } catch (IOException var20) { + var16 = MidmResponse.getResponse(432, "Failed to save the file."); + } finally { + conn.disconnect(); + } + + return var16; + } + } + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false,defaultValue = "0") long lastModified, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + String name = null; + if (fileUuid == null) { + fileUuid = UUID.randomUUID(); + notifyToUpdate = false; + } else { + BaseFile baseFile = this.fileService.findFile(fileUuid); + if (baseFile != null) { + name = baseFile.getName(); + } + } + + String filePath = this.fileService.getFilePath(user.getSiteUuid(), "other", fileUuid); + McFile targetFile = new McFile(filePath); + + try { + return this.writeFile(user, fileUuid, file.getInputStream(), targetFile, file.getOriginalFilename(), name, file.getContentType(), lastModified, (String)null, notifyToUpdate, request.getParameterMap()); + } catch (IOException var14) { + return MidmResponse.getFailedResponse(); + } + } + } + + private String writeFile(User user, UUID fileUuid, InputStream input, McFile targetFile, String fileName, String name, String contentType, long lastModified, String url, boolean notifyToUpdate, Map params) { + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + if (targetFile.write(input)) { + if (Strings.isNullOrEmpty(name)) { + name = this.findName(user.getSiteUuid(), fileUuid, fileName); + } + + boolean keepInHost = Strings.isNullOrEmpty(url); + BaseFile baseFile = new BaseFile(user, fileUuid, targetFile); + baseFile.setExtra(params); + baseFile.setSiteUuid(user.getSiteUuid()); + baseFile.setFileName(fileName); + baseFile.setName(name); + baseFile.setType(contentType); + if (contentType.endsWith("json")) { + JsonElement jElement = McJsonUtils.toJsonElement(targetFile); + if (jElement != null && jElement.isJsonObject() && jElement.getAsJsonObject().has("milock")) { + baseFile.setFileInfo("for", "milock"); + } + } + + if (!keepInHost) { + baseFile.setFileUrl(url); + targetFile.delete(); + } + + baseFile.setLastModified(lastModified); + this.fileService.save(baseFile); + if (this.cloudStorageService.hasCloudStorage() && keepInHost) { + this.cloudStorageService.upload(targetFile, fileName, targetFile.getContentType(), user.getSiteUuid(), "other", fileUuid); + } + + if (notifyToUpdate) { + this.notifyUpdate(fileUuid, true); + } + + return MidmResponse.getSucceedResponse((Object)baseFile); + } else { + targetFile.delete(); + return MidmResponse.getResponse(400, "Can't save file."); + } + } + + private String findName(UUID siteUuid, UUID fileUuid, String label) { + String name = label; + + for(int i = 1; this.fileService.nameExists(siteUuid, fileUuid, name, BaseFile.class); name = String.format("%s (%d)", label, i++)) { + } + + return name; + } + + private void notifyUpdate(UUID uuid, Boolean notifyToUpdate) { + List profiles = this.profileService.findAllByFile(uuid); + if (profiles != null && !profiles.isEmpty()) { + for(DeviceProfile profile : profiles) { + profile.setUpdated(); + this.profileService.save(profile); + if (notifyToUpdate && profile.getEnabled()) { + this.profileService.notifyUpdate(profile, false); + } + } + + } + } +} diff --git a/src/main/java/com/midm/webservice/files/GooglePlayApi.java b/src/main/java/com/midm/webservice/files/GooglePlayApi.java new file mode 100644 index 0000000..37a2d9e --- /dev/null +++ b/src/main/java/com/midm/webservice/files/GooglePlayApi.java @@ -0,0 +1,58 @@ +package com.midm.webservice.files; + +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.service.org.UserService; +import com.mitac.cell.internet.app.McPlayMarket; +import com.mitac.cell.internet.app.PlayApp; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/play"}) +public class GooglePlayApi { + @Autowired + private UserService userService; + + @RequestMapping( + value = {"/app/{packageName}"}, + method = {RequestMethod.GET}, + headers = {"Accept=*/*"}, + produces = {"application/json"} + ) + @ResponseBody + public String getApkInfo(HttpServletRequest request, Authentication authentication, @PathVariable String packageName, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + PlayApp app = McPlayMarket.getApkInfo(packageName, user.getLocale()); + return app == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse((Object)app); + } + } + + @RequestMapping( + value = {"/search"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String search(HttpServletRequest request, Authentication authentication, @RequestParam String key, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List apps = McPlayMarket.search(key, user.getLocale()); + return apps == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse(apps); + } + } +} diff --git a/src/main/java/com/midm/webservice/files/OtasApi.java b/src/main/java/com/midm/webservice/files/OtasApi.java new file mode 100644 index 0000000..e502170 --- /dev/null +++ b/src/main/java/com/midm/webservice/files/OtasApi.java @@ -0,0 +1,450 @@ +package com.midm.webservice.files; + +import com.google.common.base.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.model.device.DeviceProfile; +import com.midm.model.file.OtaFile; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.ProfileService; +import com.midm.service.file.FileService; +import com.midm.service.org.UserService; +import com.mitac.cell.internet.http.McHttpClient; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McUrlUtils; +import com.mongodb.client.result.UpdateResult; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLDecoder; +import java.nio.charset.Charset; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/otas"}) +public class OtasApi { + @Autowired + private FileService fileService; + @Autowired + private ProfileService profileService; + @Autowired + private UserService userService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (filter == null) { + filter = new JsonObject(); + } + + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(415, "User is not belonged to the site."); + } else { + if (!filter.has("siteUuid")) { + filter.addProperty("siteUuid", siteUuid.toString()); + } + + Page pageResult = this.fileService.findOtas(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(415, "User is not belonged to the site."); + } else { + List otas = this.fileService.findOtas(siteUuid, filter, sortBy, direction); + return MidmResponse.getSucceedResponse(otas); + } + } + } + + @RequestMapping( + value = {"/info/{uuid}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String info(HttpServletRequest request, Authentication authentication, @PathVariable UUID uuid, @RequestParam(required = false) String fingerPrint, @RequestParam(required = false,defaultValue = "-1") long buildDate) { + OtaFile otaFile = this.fileService.findOta(uuid); + if (otaFile == null) { + return MidmResponse.getFailedResponse(); + } else if (buildDate > 0L && buildDate == otaFile.getBuildDate()) { + return MidmResponse.getSucceedResponse(); + } else { + return otaFile.isPartial() && !Strings.isNullOrEmpty(fingerPrint) && !fingerPrint.equals(otaFile.getPreBuild()) ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse((Object)otaFile); + } + } + + @RequestMapping( + value = {"/info"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String infos(HttpServletRequest request, Authentication authentication, @RequestParam List uuids, @RequestParam String deviceId, @RequestParam(required = false) String fingerPrint, @RequestParam(required = false,defaultValue = "true") Boolean partialFirst, @RequestParam(required = false,defaultValue = "-1") Long buildDate, @RequestParam(required = false) String customerId, @RequestParam(required = false) String skuId, @RequestParam(required = false) String scriptVersion, @RequestParam(required = false,defaultValue = "-1") long regionBuildDate, @RequestParam(required = false,defaultValue = "false") boolean ignorePartNo, @RequestParam(required = false,defaultValue = "false") boolean checkBuildDate) { + if (!Strings.isNullOrEmpty(fingerPrint)) { + fingerPrint = URLDecoder.decode(fingerPrint, Charset.defaultCharset()); + } + + OtaFile otaFile = this.fileService.findOta(uuids, deviceId, skuId, customerId, scriptVersion, regionBuildDate, fingerPrint, buildDate, partialFirst, ignorePartNo, checkBuildDate); + return otaFile != null ? MidmResponse.getSucceedResponse((Object)otaFile) : MidmResponse.getResponse(404, "No OTA image found to update."); + } + + @RequestMapping( + value = {"/rename"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String rename(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID fileUuid, @RequestParam String name) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.fileService.rename(fileUuid, name, OtaFile.class); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/nameExists"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String nameExists(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String name) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean exists = this.fileService.nameExists(user.getSiteUuid(), (UUID)null, name, OtaFile.class); + return MidmResponse.getSucceedResponse((Object)exists); + } + } + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + OtaFile ota = (OtaFile)McJsonUtils.toObject(request, OtaFile.class); + if (!user.canHandle(ota.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.fileService.save(ota); + return MidmResponse.getSucceedResponse((Object)ota); + } + } + } + + @RequestMapping( + value = {"/updateExtras"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateExtras(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!this.fileService.existsById(OtaFile.class, uuid)) { + return MidmResponse.getResponse(421, "No apps found."); + } else { + UpdateResult result = this.fileService.updateExtras(OtaFile.class, uuid, request.getParameterMap()); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + OtaFile ota = (OtaFile)McJsonUtils.toObject(request, OtaFile.class); + if (!user.canHandle(ota.getSiteUuid(), UserRole.PROFILE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.fileService.delete(user.getSiteUuid(), ota); + return MidmResponse.getSucceedResponse((Object)ota); + } + } + } + + @RequestMapping( + value = {"/addLink"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String addLink(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false) URL url, @RequestParam(required = false) Boolean keepInHost, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + JsonElement jReference = McJsonUtils.toJsonElement(request); + JsonObject reference = jReference == null ? new JsonObject() : jReference.getAsJsonObject(); + String link = reference.get("url").getAsString(); + if (keepInHost == null) { + keepInHost = McJsonUtils.getBoolean(reference, "keepInHost", false); + } + + if (url == null) { + url = McUrlUtils.toUrl(link); + } + + HttpURLConnection conn = McHttpClient.open(url); + if (conn == null) { + return MidmResponse.getResponse(432, "The given link is not able to connect."); + } else { + String originalFileName = McHttpClient.getFileName(conn); + String contentType = conn.getContentType(); + if ((Strings.isNullOrEmpty(originalFileName) || !originalFileName.endsWith(".zip")) && !Strings.isNullOrEmpty(contentType) && !contentType.startsWith("application/zip") && contentType.equals("application/octet-stream")) { + conn.disconnect(); + return MidmResponse.getResponse(400, "The given link seems invalid system image."); + } else { + String name = null; + if (fileUuid == null) { + fileUuid = UUID.randomUUID(); + notifyToUpdate = false; + } else { + OtaFile otaFile = this.fileService.findOta(fileUuid); + if (otaFile != null) { + if (!user.isBelongedToSite(otaFile.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } + + name = otaFile.getName(); + } + } + + String filePath = this.fileService.getFilePath(user.getSiteUuid(), "ota", fileUuid); + McFile targetFile = new McFile(filePath); + + String var19; + try { + String result = this.writeFile(user, fileUuid, conn.getInputStream(), targetFile, originalFileName, name, conn.getLastModified(), keepInHost ? null : link, notifyToUpdate, request.getParameterMap()); + var19 = result; + return var19; + } catch (IOException var23) { + var19 = MidmResponse.getResponse(432, "Failed to save the file."); + } finally { + conn.disconnect(); + } + + return var19; + } + } + } + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam MultipartFile file, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false,defaultValue = "0") long lastModified, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!file.getContentType().endsWith("zip") && !file.getContentType().endsWith("x-zip-compressed")) { + return MidmResponse.getResponse(441, "Invalid system image."); + } else { + String fileName = file.getOriginalFilename(); + OtaFile ota = null; + String orgName = null; + if (fileUuid != null) { + ota = this.fileService.findOta(fileUuid); + if (ota != null) { + if (!user.isBelongedToSite(ota.getSiteUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } + + orgName = ota.getName(); + } + } else { + fileUuid = UUID.randomUUID(); + notifyToUpdate = false; + } + + String filePath = this.fileService.getFilePath(user.getSiteUuid(), "ota", fileUuid); + McFile targetFile = new McFile(filePath); + + try { + return this.writeFile(user, fileUuid, file.getInputStream(), targetFile, fileName, orgName, lastModified, (String)null, notifyToUpdate, request.getParameterMap()); + } catch (IOException var16) { + return MidmResponse.getFailedResponse(); + } + } + } + + private String writeFile(User user, UUID fileUuid, InputStream input, McFile targetFile, String fileName, String name, long lastModified, String url, boolean notifyToUpdate, Map params) { + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + if (targetFile.write(input)) { + OtaFile ota = new OtaFile(user, fileUuid, targetFile); + ota.setExtra(params); + boolean keepInHost = Strings.isNullOrEmpty(url); + if (Strings.isNullOrEmpty(ota.getProductId())) { + int endIndex = fileName.indexOf(95); + if (endIndex > 0) { + String productId = fileName.substring(0, endIndex); + if (!Strings.isNullOrEmpty(productId)) { + ota.setProductId(productId); + } + + int startIndex = endIndex + 1; + endIndex = fileName.lastIndexOf(95); + if (startIndex < endIndex) { + String displayId = fileName.substring(startIndex, endIndex); + if (!Strings.isNullOrEmpty(displayId)) { + ota.setDisplayId(displayId); + } + } + } + } + + if (Strings.isNullOrEmpty(ota.getDisplayId())) { + int startIndex = fileName.indexOf(95) + 1; + int endIndex = fileName.lastIndexOf(95); + if (startIndex < endIndex) { + String displayId = fileName.substring(startIndex, endIndex); + if (!Strings.isNullOrEmpty(displayId)) { + ota.setDisplayId(displayId); + } + } + } + + if (!ota.isRegionImage() && Strings.isNullOrEmpty(ota.getSkuId())) { + String skuId = OtaFile.parseSkuId(fileName); + if (!Strings.isNullOrEmpty(skuId)) { + ota.setSkuId(skuId); + } + } + + if (ota.isOtaImage()) { + ota.setSiteUuid(user.getSiteUuid()); + ota.setFileName(fileName); + if (Strings.isNullOrEmpty(name)) { + name = this.findName(user.getSiteUuid(), fileUuid, ota.getDeviceId()); + } + + ota.setName(name); + if (!keepInHost) { + ota.setFileUrl(url); + targetFile.delete(); + } + + ota.setLastModified(lastModified); + this.fileService.save(ota); + if (this.cloudStorageService.hasCloudStorage() && keepInHost) { + this.cloudStorageService.upload(targetFile, fileName, targetFile.getContentType(), user.getSiteUuid(), "ota", fileUuid); + } + + if (notifyToUpdate) { + this.notifyUpdate(fileUuid, true); + } + + return MidmResponse.getSucceedResponse((Object)ota); + } + } + + targetFile.delete(); + return MidmResponse.getResponse(441, "Invalid system image."); + } + + private String findName(UUID siteUuid, UUID fileUuid, String label) { + String name = label; + + for(int i = 1; this.fileService.nameExists(siteUuid, fileUuid, name, OtaFile.class); name = String.format("%s (%d)", label, i++)) { + } + + return name; + } + + private void notifyUpdate(UUID uuid, Boolean notifyToUpdate) { + List profiles = this.profileService.findAllByOta(uuid); + if (profiles != null && !profiles.isEmpty()) { + for(DeviceProfile profile : profiles) { + profile.setUpdated(); + this.profileService.save(profile); + if (notifyToUpdate && profile.getEnabled()) { + this.profileService.notifyUpdate(profile, false); + } + } + + } + } +} diff --git a/src/main/java/com/midm/webservice/files/ReportApi.java b/src/main/java/com/midm/webservice/files/ReportApi.java new file mode 100644 index 0000000..c77ef9c --- /dev/null +++ b/src/main/java/com/midm/webservice/files/ReportApi.java @@ -0,0 +1,263 @@ +package com.midm.webservice.files; + +import com.google.gson.JsonObject; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.SiteFile; +import com.midm.model.org.User; +import com.midm.model.org.UserRole; +import com.midm.service.file.ReportService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.TimeZone; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/report"}) +public class ReportApi { + @Autowired + private SiteService siteService; + @Autowired + private ReportService reportService; + @Autowired + private UserService userService; + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (size == null) { + size = Integer.MAX_VALUE; + } + + Page pageResult = this.reportService.findReports(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/request/{category}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String category, @RequestBody(required = false) DbObject settings, @CookieValue(required = false) TimeZone timeZone, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) Set sites, @RequestParam(required = false,defaultValue = "true") boolean keep, @RequestParam(required = false,defaultValue = "false") boolean mailMe, @RequestParam(name = "timeOffset",required = false) Integer minOffset) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site; + if (siteUuid != null && !siteUuid.equals(user.getSiteUuid())) { + if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(433, "No permission."); + } + + site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } + } else { + site = user.getSite(); + siteUuid = site.getUuid(); + } + + if (minOffset == null) { + if (timeZone == null) { + timeZone = user.getSite().getTimeZone(); + } + + if (timeZone != null) { + minOffset = timeZone.getRawOffset() / '\uea60'; + } else { + minOffset = 0; + } + } + + if (settings != null && settings.containsKey("groups")) { + List groups = settings.getList("groups", UUID.class); + settings.put("groups", groups); + } + + if (keep) { + DbObject reportSetting = user.getSiteInfo(user.getSiteUuid()).getSettings().getDbObject(new String[]{"report"}); + reportSetting.put(category, settings); + reportSetting.put("mailMe", mailMe); + this.userService.updateAuthorizedUser(user); + this.userService.setSiteSetting(user, "report", reportSetting); + } + + switch (category) { + case "site": + String siteOption = settings != null ? settings.getString("siteOption", "mine") : (sites != null ? "selected" : "mine"); + DbObject itemSettings = settings != null ? settings.getDbObject(new String[]{"item"}) : new DbObject(); + if (siteOption.equals("mine")) { + this.reportService.generateSiteReport(user, site, (Site)null, minOffset, itemSettings, mailMe); + } else { + List childSites = new ArrayList(); + Collection childUuids = (Collection)(sites != null ? sites : (settings != null ? settings.getList("sites", UUID.class) : null)); + if (childUuids != null && !childUuids.isEmpty()) { + for(UUID childUuid : childUuids) { + Site childSite = this.siteService.findByUuid(childUuid); + if (childSite == null) { + return MidmResponse.getResponse(451, "No site available."); + } + + if (childSite.getReseller() == null || !siteUuid.equals(childSite.getReseller().getUuid())) { + return MidmResponse.getResponse(433, "No permission."); + } + + childSites.add(childSite); + } + } + + if (childSites.isEmpty()) { + return MidmResponse.getResponse(451, "No site available."); + } + + for(Site childSite : childSites) { + this.reportService.generateSiteReport(user, site, childSite, minOffset, itemSettings, mailMe); + } + } + break; + case "device": + this.reportService.generateDeviceReport(user, site, settings, minOffset, mailMe); + break; + case "profile": + this.reportService.generateProfileReport(user, site, settings, minOffset, mailMe); + } + + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"template/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String fileName) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + String filePath = this.reportService.getTemplateFilePath(fileName + ".xlsx"); + McFile targetFile = new McFile(filePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + try { + targetFile.write(file.getInputStream()); + return MidmResponse.getSucceedResponse(); + } catch (IOException e) { + return MidmResponse.getResponse(400, e.getMessage()); + } + } + } + + @RequestMapping( + value = {"/installedApps"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getInstalled(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getSiteUuid(); + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } + + if (!user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(433, "No permission."); + } + } + + return MidmResponse.getSucceedResponse((Object)this.reportService.installedApps(siteUuid)); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + SiteFile siteReport = (SiteFile)McJsonUtils.toObject(request, SiteFile.class); + UUID siteUuid = siteReport.getSiteUuid(); + if (!user.canHandle(siteUuid, UserRole.DEVICE_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.reportService.delete(siteReport); + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/findone"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findone(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(412, "No user logged in."); + } else { + SiteFile siteReport = this.reportService.findReportByUuid(fileUuid); + if (siteReport == null) { + return MidmResponse.getResponse(421, "No reports."); + } else { + return !user.canHandle(siteReport.getSiteUuid(), UserRole.DEVICE_MANAGE_ROLES) ? MidmResponse.getResponse(433, "No permission.") : MidmResponse.getSucceedResponse((Object)siteReport); + } + } + } +} diff --git a/src/main/java/com/midm/webservice/log/LogsApi.java b/src/main/java/com/midm/webservice/log/LogsApi.java new file mode 100644 index 0000000..a3c6ca0 --- /dev/null +++ b/src/main/java/com/midm/webservice/log/LogsApi.java @@ -0,0 +1,102 @@ +package com.midm.webservice.log; + +import com.midm.model.log.MidmLog; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.service.log.LogService; +import com.midm.service.org.UserService; +import com.mitac.cell.utils.McJsonUtils; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/logs"}) +public class LogsApi { + @Autowired + private UserService userService; + @Autowired + private LogService logService; + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) String direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Page pageResult = this.logService.findLogs(filter, page, size, sortBy, direction); + + for(MidmLog log : pageResult) { + User user = this.userService.findUserByUserUuid(log.getLoggerUuid()); + if (user != null) { + log.setLogger(user); + } + } + + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, @RequestParam(required = false) List uuids) { + if (uuids == null) { + MidmLog log = (MidmLog)McJsonUtils.toObject(request, MidmLog.class); + return MidmResponse.getSucceedResponse((Object)this.logService.delete(log)); + } else { + return MidmResponse.getSucceedResponse((Object)this.logService.delete(uuids)); + } + } + + @RequestMapping( + value = {"/clear"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String clearAllLogs(HttpServletRequest request, Principal principal, @RequestParam(required = true) UUID uuid) { + this.logService.clearAllLogsFor(uuid); + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/clear/device"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String clearAllDeviceLogs(HttpServletRequest request, Principal principal, @RequestParam(required = true) UUID deviceUuid) { + this.logService.clearAllLogsFor(deviceUuid); + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/clear/user"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String clearAllUserLogs(HttpServletRequest request, Principal principal, @RequestParam(required = true) UUID userUuid) { + this.logService.clearAllLogsFor(userUuid); + return MidmResponse.getSucceedResponse(); + } +} diff --git a/src/main/java/com/midm/webservice/news/NewsMessageApi.java b/src/main/java/com/midm/webservice/news/NewsMessageApi.java new file mode 100644 index 0000000..652fcec --- /dev/null +++ b/src/main/java/com/midm/webservice/news/NewsMessageApi.java @@ -0,0 +1,271 @@ +package com.midm.webservice.news; + +import com.google.gson.JsonObject; +import com.midm.model.device.Device; +import com.midm.model.message.MidmResponse; +import com.midm.model.news.MessageLog; +import com.midm.model.news.NewsMessage; +import com.midm.model.org.User; +import com.midm.service.news.MessageLogService; +import com.midm.service.news.NewsMessageService; +import com.midm.service.org.UserService; +import com.mitac.cell.utils.McJsonUtils; +import com.mongodb.client.result.UpdateResult; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/news"}) +public class NewsMessageApi { + @Autowired + private UserService userService; + @Autowired + private NewsMessageService newsMessageService; + @Autowired + private MessageLogService messageLogService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, HttpServletResponse response, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID uuid, @RequestParam(required = false) Boolean sendNow, @RequestParam(required = false) Device device) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + NewsMessage message = (NewsMessage)McJsonUtils.toObject(request, NewsMessage.class); + message.setWriter(user); + this.newsMessageService.save(message); + if (!sendNow && !message.getForWhat().equals("urgent")) { + this.newsMessageService.saveMessageLog(message); + } else { + this.newsMessageService.notifyMessage(message); + } + + return MidmResponse.getSucceedResponse((Object)message); + } + } + + @RequestMapping( + value = {"/saveLog"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveLog(HttpServletRequest request, HttpServletResponse response, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + MessageLog messageLog = (MessageLog)McJsonUtils.toObject(request, MessageLog.class); + messageLog.setReader(user); + this.newsMessageService.saveMessageLog(messageLog); + return MidmResponse.getSucceedResponse((Object)messageLog); + } + } + + @RequestMapping( + value = {"/deleteFromSite"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteFromSite(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + MessageLog messageLog = (MessageLog)McJsonUtils.toObject(request, MessageLog.class); + this.newsMessageService.delete(messageLog); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/findAllFromSite"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) int limit) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List logs = this.newsMessageService.findLogsByUserAndSite(user, limit); + return MidmResponse.getSucceedResponse(logs); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAllNewsMessage(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String category, @RequestParam(required = false) String forWhat, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false) JsonObject filter) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Page pageResult = this.newsMessageService.find(category, forWhat, filter, sortBy, direction, page, size); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/deleteFromAdmin"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteFromAdmin(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + NewsMessage newsMessage = (NewsMessage)McJsonUtils.toObject(request, NewsMessage.class); + this.newsMessageService.delete(newsMessage); + return MidmResponse.getSucceedResponse((Object)newsMessage); + } + } + + @RequestMapping( + value = {"/markAsRead"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String markAsRead(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UpdateResult result = this.newsMessageService.markAllMessageAsRead(user, siteUuid); + return MidmResponse.getSucceedResponse((Object)result.getModifiedCount()); + } + } + + @RequestMapping( + value = {"/recents"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String recentMessages(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,defaultValue = "10") int limit) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Document recents = this.newsMessageService.recentMessages(user, limit); + return MidmResponse.getSucceedResponse((Object)recents); + } + } + + @RequestMapping( + value = {"/unchecked"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String unchecked(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,defaultValue = "10") int limit) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List unchecked = this.messageLogService.findUnchecked(user); + return MidmResponse.getSucceedResponse(unchecked); + } + } + + @RequestMapping( + value = {"/count"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String countUnread(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + long countUnread = this.newsMessageService.countUnread(user); + return MidmResponse.getSucceedResponse((Object)countUnread); + } + } + + @RequestMapping( + value = {"/setAsCheck"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String setMessageAscheck(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UpdateResult result = this.newsMessageService.setMessageAsCheck(user); + return MidmResponse.getSucceedResponse((Object)result.getModifiedCount()); + } + } + + @RequestMapping( + value = {"/setOneAsChecked"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String setOneMessageAsCheck(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID messageLogUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UpdateResult result = this.newsMessageService.setMessageAsCheck(messageLogUuid); + return MidmResponse.getSucceedResponse((Object)result.getModifiedCount()); + } + } + + @RequestMapping( + value = {"/sendExpiring"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String sendLicenseExpiringMessage() { + this.newsMessageService.licenseExpirySendMessage(); + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/getPopUpTemplate"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getPopUpTemplate(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID newsUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + String html = this.newsMessageService.getHtml((NewsMessage)null, newsUuid); + return html != null ? MidmResponse.getSucceedResponse((Object)html) : MidmResponse.getResponse(421, "NewsMessage not found."); + } + } +} diff --git a/src/main/java/com/midm/webservice/org/SiteApi.java b/src/main/java/com/midm/webservice/org/SiteApi.java new file mode 100644 index 0000000..d8e9a48 --- /dev/null +++ b/src/main/java/com/midm/webservice/org/SiteApi.java @@ -0,0 +1,637 @@ +package com.midm.webservice.org; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.controller.lib.FilesController; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.SiteInfo; +import com.midm.model.org.SiteRequest; +import com.midm.model.org.User; +import com.midm.model.org.UserGroup; +import com.midm.model.org.UserRole; +import com.midm.security.UserPrincipal; +import com.midm.service.EmailService; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.device.DeviceService; +import com.midm.service.file.FileService; +import com.midm.service.log.LogService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.io.McFile; +import com.mitac.cell.io.McResource; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.UpdateResult; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.security.Principal; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import javax.imageio.ImageIO; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.http.entity.ContentType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/site"}) +public class SiteApi { + @Autowired + private ServletContext servletContext; + @Autowired + private UserService userService; + @Autowired + private SiteService siteService; + @Autowired + private DeviceService deviceService; + @Autowired + private HostLicenseService hostLicenseService; + @Autowired + private FileService fileService; + @Autowired + private EmailService emailService; + @Autowired + private LogService logService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String register(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestBody Site site) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean exists = site.getUuid() != null; + if (!exists) { + Site userSite = user.getSite(); + if (userSite != null && userSite.isReseller() && user.hasRole("SUPERVISOR")) { + site.setReseller(userSite); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SITE_MANAGER")) { + return MidmResponse.getResponse(433, "No permission."); + } + } + + site = this.siteService.save(site); + if (site.isUpgradeRequested()) { + this.siteService.sendMessageToRecipients(site); + this.logService.save(user, site.getUuid(), "activity", String.format("Site [%s] upgrade SiteLicense request from [%s] to [%s]", site.getIdName(), site.getPlanName(), site.getUpgradeTargetPlan())); + } + + if (!exists) { + this.logService.save(user, site.getUuid(), "activity", String.format("New site has added: %s", site.getIdName())); + } else { + this.logService.save(user, site.getUuid(), "update", exists ? "Updated" : "Registered"); + } + + return MidmResponse.getSucceedResponse((Object)site); + } + } + + @RequestMapping( + value = {"/setSettings"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String setSetting(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestBody DbObject settings) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getLastSite(); + } + + if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.canHandle(siteUuid, "SUPERVISOR")) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UpdateResult result = this.siteService.setSetting(siteUuid, settings); + if (result.getModifiedCount() > 0L) { + this.logService.save(user, siteUuid, "update", "Site settings changed."); + } + + return result != null ? MidmResponse.getSucceedResponse() : MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/updateProfile"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateProfile(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestBody DbObject profile) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getLastSite(); + } + + if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.canHandle(siteUuid, "SUPERVISOR")) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + UpdateResult result = this.siteService.updateProfile(siteUuid, profile); + if (result.getModifiedCount() > 0L) { + this.logService.save(user, siteUuid, "update", "Site profile updated."); + } + + return result != null ? MidmResponse.getSucceedResponse() : MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/setting/{key}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getSetting(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @PathVariable String key) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getLastSite(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.canHandle(siteUuid, "SUPERVISOR")) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } else { + Object setting = site.getSetting(key); + return setting == null ? MidmResponse.getResponse(421, String.format("The setting(%s) is not configured.", key)) : MidmResponse.getSucceedResponse(setting); + } + } + } + } + + @RequestMapping( + value = {"/getCredential"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getCredential(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getLastSite(); + } + + if (siteUuid == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.canHandle(siteUuid, "SUPERVISOR")) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } else { + DbObject credential = site.getCredential(); + return credential != null && !credential.isEmpty() ? MidmResponse.getSucceedResponse((Object)credential) : MidmResponse.getResponse(421, "No credential defined."); + } + } + } + } + + @RequestMapping( + value = {"/updateCredential"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateCredential(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String credential) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = user.getLastSite(); + } + + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (!user.canHandle(siteUuid, "SUPERVISOR")) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + site.setCredential(credential); + UpdateResult result = this.siteService.updateCredential(siteUuid, site.getCredential()); + return MidmResponse.getSucceedResponse((Object)result.getModifiedCount()); + } + } + } + + @RequestMapping( + value = {"/enableSetting"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String enableSetting(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String key, @RequestParam boolean value) { + User user = this.userService.authorizedUser(authentication, accessToken); + return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse((Object)this.siteService.setSetting(user.getSiteUuid(), key, value).getModifiedCount()); + } + + @RequestMapping( + value = {"/enable"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String enableSites(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,name = "uuid") List uuids, @RequestParam(required = false) boolean enabled) { + User loggeduser = this.userService.authorizedUser(authentication, accessToken); + if (loggeduser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.siteService.enableSites(uuids, enabled); + uuids.forEach((uuid) -> this.logService.save(loggeduser, uuid, "activity", String.format("Site is %s by %s.", enabled ? "enabled" : "disabled", loggeduser.getName()))); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String model, @RequestParam(required = false) String plan, @RequestParam(required = false) String sortBy, @RequestParam(required = false) boolean updateReport) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasRole("SUPERVISOR") && !user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SITE_MANAGER") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + List siteList = this.siteService.findAll(user.getSite(), model, plan, sortBy, updateReport); + return MidmResponse.getSucceedResponse(siteList); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasRole("SUPERVISOR") && !user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SITE_MANAGER")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.siteService.find(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/exists"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String exists(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String idName) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean exists = this.siteService.exists(idName); + return MidmResponse.getSucceedResponse((Object)exists); + } + } + + @RequestMapping( + value = {"/getStandalone"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getStandalone(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String plan) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List standalones = this.siteService.getByPlan(plan); + return MidmResponse.getSucceedResponse(standalones); + } + } + + @RequestMapping( + value = {"/findBy"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findBy(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String id, @RequestParam(required = false) UUID uuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = null; + if (uuid != null) { + site = this.siteService.findByUuid(uuid); + } + + if (site == null && McStringUtils.isValid(id)) { + site = this.siteService.findByIdName(id); + } + + return site == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse((Object)site); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID siteUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } else if (user.hasSystemRole("SYSTEM_ADMIN") || user.hasSystemRole("SITE_MANAGER") || user.hasRole("SUPERVISOR") && user.isBelongedToSite(site.getReseller().getUuid())) { + if (this.hostLicenseService.isStandalone() && this.hostLicenseService.getDeviceLimit() > 0 && this.deviceService.getDeviceCount(siteUuid) > 0L) { + return MidmResponse.getResponse(467, "Existing device."); + } else { + if (site.isReseller()) { + List childSites = this.siteService.findAllChilds(site); + if (childSites.size() > 0 && user.isSystemUser()) { + childSites.forEach((childSite) -> this.siteService.delete(childSite, user)); + } + } + + this.siteService.delete(site, user); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(433, "No permission."); + } + } + } + + @RequestMapping( + value = {"/addUser"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String addUser(HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) String email, @RequestParam(required = false) UUID groupUuid, @RequestParam(required = false) String groupPath, @RequestParam(required = false,defaultValue = "") Set roles) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site == null) { + return MidmResponse.getResponse(451, "Not authorized."); + } else { + siteUuid = site.getUuid(); + if (loggedUser != null && loggedUser.canHandle(siteUuid, UserRole.USER_MANAGE_ROLES)) { + User user = this.userService.findUser(userUuid, email); + if (user == null) { + return MidmResponse.getResponse(421, "No user exists."); + } else if (user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(455, "Already belongs to the site."); + } else { + SiteInfo siteInfo = user.addSite(siteUuid); + UserGroup group = null; + if (groupUuid != null) { + group = this.userService.findUserGroup(groupUuid); + } + + if (group == null && !Strings.isNullOrEmpty(groupPath)) { + group = this.userService.findUserGroup(siteUuid, groupPath); + } + + if (group != null) { + siteInfo.setGroupUuid(group.getUuid()); + } + + if (!roles.isEmpty()) { + siteInfo.setRoles(roles); + } + + this.userService.addSite(user, siteInfo); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + } + + @RequestMapping( + value = {"/background"}, + method = {RequestMethod.GET} + ) + public void backgroundImage(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + UUID siteUuid = user.getSiteUuid(); + if (siteUuid != null) { + String url = this.cloudStorageService.getUrl(siteUuid, "background"); + if (Strings.isNullOrEmpty(url)) { + String profilePath = this.fileService.getSiteFilePath(siteUuid, "background"); + String fileName = "background.jpg"; + McFile file = new McFile(profilePath); + if (file.exists()) { + McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "background.jpg", 0, -1); + } else { + FilesController.forwardRequest(request, response, "/image/bg/background.jpg"); + } + } else { + try { + response.sendRedirect(url); + } catch (IOException var10) { + FilesController.forwardRequest(request, response, "/image/bg/background.jpg"); + } + } + } + } + + } + + @RequestMapping( + value = {"/titleLogo"}, + method = {RequestMethod.GET} + ) + public void headerLogo(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + UUID siteUuid = user.getSiteUuid(); + if (siteUuid != null) { + String url = this.cloudStorageService.getUrl(siteUuid, "logo"); + if (Strings.isNullOrEmpty(url)) { + String profilePath = this.fileService.getSiteFilePath(siteUuid, "logo"); + String fileName = "logo.jpg"; + McFile file = new McFile(profilePath); + if (file.exists()) { + McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "logo.jpg", 0, -1); + } else { + try { + response.sendError(404); + } catch (Exception var12) { + FilesController.forwardRequest(request, response, "/image/empty.png"); + } + } + } else { + try { + response.sendRedirect(url); + } catch (IOException var11) { + FilesController.forwardRequest(request, response, "/image/empty.png"); + } + } + } + + } + } + + @RequestMapping( + value = {"/{type}/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteLogo(HttpServletRequest request, Authentication authentication, @PathVariable String type) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getFailedResponse(); + } else { + Site site = this.siteService.findByUuid(user.getSiteUuid()); + if (site == null) { + return MidmResponse.getResponse(421, "No site available."); + } else { + site.getSettingsCategory(new String[]{"theme"}).remove(type); + site = this.siteService.save(site); + String profilePath = this.fileService.getSiteFilePath(site.getUuid(), type); + (new McFile(profilePath)).delete(); + this.cloudStorageService.delete(site.getUuid(), type); + return MidmResponse.getSucceedResponse((Object)site); + } + } + } + + @RequestMapping( + value = {"/requestTrial"}, + method = {RequestMethod.POST} + ) + @ResponseBody + public String requestTrial(HttpServletRequest request, HttpServletResponse response) { + SiteRequest siteRequest = (SiteRequest)McJsonUtils.toObject(request, SiteRequest.class); + this.siteService.save(siteRequest); + this.emailService.sendSiteTrial(request, response, siteRequest); + response.addHeader("Access-Control-Allow-Origin", "*"); + response.addHeader("Access-Control-Allow-Methods", "POST"); + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String type) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = null; + if (siteUuid != null) { + site = this.siteService.findByUuid(siteUuid); + } + + if (site == null) { + return MidmResponse.getFailedResponse(); + } else if (user != null && !user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String profilePath = this.fileService.getSiteFilePath(siteUuid, type); + McFile targetFile = new McFile(profilePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + try { + BufferedImage image = null; + String extension = "png"; + ContentType contentType = ContentType.IMAGE_PNG; + if (type.equals("logo")) { + image = this.fileService.getLogoImage(file); + site.setSetting("theme", type, true); + site = this.siteService.save(site); + } else if (type.equals("profile")) { + image = this.fileService.getProfileImage(file); + } else if (type.equals("background")) { + extension = "jpg"; + contentType = ContentType.IMAGE_JPEG; + image = this.fileService.getBgImage(file); + } + + ImageIO.write(image, extension, targetFile); + if (this.cloudStorageService.hasCloudStorage()) { + this.cloudStorageService.upload(targetFile, targetFile.getName() + "." + extension, contentType.toString(), user.getSiteUuid(), type); + } + + return MidmResponse.getSucceedResponse((Object)site); + } catch (Exception var14) { + if (targetFile.exists()) { + targetFile.delete(); + } + + return MidmResponse.getFailedResponse(); + } + } + } + } + + @RequestMapping( + value = {"/reorganize"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String reorganize(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String resellerId, @RequestParam(required = false) String id, @RequestParam String organize) { + return !this.siteService.reorganize(id, resellerId, organize) ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse(); + } +} diff --git a/src/main/java/com/midm/webservice/org/UserApi.java b/src/main/java/com/midm/webservice/org/UserApi.java new file mode 100644 index 0000000..9b6e7ec --- /dev/null +++ b/src/main/java/com/midm/webservice/org/UserApi.java @@ -0,0 +1,1759 @@ +package com.midm.webservice.org; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceProfile; +import com.midm.model.log.MidmLog; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.SiteInfo; +import com.midm.model.org.USER_PROPERTY; +import com.midm.model.org.User; +import com.midm.model.org.UserGroup; +import com.midm.model.org.UserRole; +import com.midm.model.org.UserToken; +import com.midm.model.system.PolicyAgreement; +import com.midm.security.UserPrincipal; +import com.midm.service.EmailService; +import com.midm.service.device.DeviceService; +import com.midm.service.device.ProfileService; +import com.midm.service.file.FileService; +import com.midm.service.log.LogService; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.PolicyAgreementService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.doc.ExcelCell; +import com.mitac.cell.doc.ExcelRow; +import com.mitac.cell.internet.http.McResponse; +import com.mitac.cell.internet.http.UserAgent; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McEmailUtils; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.result.UpdateResult; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; +import java.util.UUID; +import javax.imageio.ImageIO; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/user"}) +public class UserApi { + @Autowired + private UserService userService; + @Autowired + private PolicyAgreementService policyAgreementService; + @Autowired + private FileService fileService; + @Autowired + private DeviceService deviceService; + @Autowired + private SiteService siteService; + @Autowired + private ProfileService profileService; + @Autowired + private HostLicenseService hostLicenseService; + @Autowired + private LogService logService; + @Autowired + private WebSocketSessionManager sessionManager; + @Autowired + private SettingsService settingsService; + @Autowired + private PasswordEncoder passwordEncoder; + @Autowired + private EmailService emailService; + private Map columns = null; + private int emailColumnIndex; + + @RequestMapping( + value = {"/login"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String login(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @CookieValue(required = false) TimeZone timeZone, @CookieValue(value = "JSESSIONID",defaultValue = "") String sessionId, @RequestHeader(value = "User-Agent",defaultValue = "") UserAgent userAgent, @RequestParam(required = false) String email, @RequestParam(required = false) String password, @RequestParam(required = false,defaultValue = "false") Boolean forceToLogout, @RequestParam(required = false,defaultValue = "false") Boolean bypassEula, @RequestParam(required = false,defaultValue = "false") Boolean keepSignIn, @RequestParam(required = false) UUID eulaUuid) { + if (Strings.isNullOrEmpty(email)) { + DbObject params = (DbObject)McJsonUtils.toObject(request, DbObject.class); + if (params != null) { + email = params.getString("email"); + if (Strings.isNullOrEmpty(password)) { + password = params.getString("password"); + } + + if (params.containsKey("forceToLogout")) { + forceToLogout = params.getBoolean("forceToLogout", forceToLogout); + } + + if (params.containsKey("bypassEula")) { + bypassEula = params.getBoolean("bypassEula", bypassEula); + } + + if (params.containsKey("keepSignIn")) { + keepSignIn = params.getBoolean("keepSignIn", keepSignIn); + } + + if (eulaUuid == null && params.containsKey("eulaUuid")) { + eulaUuid = params.getUuid("eulaUuid"); + } + } + } + + if (!Strings.isNullOrEmpty(email) && !Strings.isNullOrEmpty(password)) { + String remoteIp = request.getRemoteAddr(); + email = URLDecoder.decode(email, Charset.defaultCharset()); + User user = this.userService.findUserByEmail(email.trim()); + if (user == null) { + return MidmResponse.getResponse(410, "Email or password is wrong."); + } else if (!user.isAvailable()) { + return MidmResponse.getResponse(412, "Account may not activated."); + } else if (!this.hostLicenseService.isValid() && !user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(420, "Host is expired."); + } else { + DbObject loginAttempt = user.getLoginAttempt(); + int attemptCount = loginAttempt.getInteger("count", 0); + if (attemptCount >= 5) { + Date lastAttempt = loginAttempt.getDate("attemptAt"); + DateTime nextTryAfter = (new DateTime(lastAttempt)).plusMinutes(10); + if (lastAttempt != null && nextTryAfter.isAfterNow()) { + loginAttempt.append("tryAfter", nextTryAfter.toDate()); + return MidmResponse.getResponse(424, String.format("Login failed more than %d times.", 5), loginAttempt); + } + + user.resetLoginAttempt(); + } + + if (!this.userService.matchPassword(user, password)) { + this.userService.updateLoginAttempt(user, false); + loginAttempt = user.getLoginAttempt(); + attemptCount = loginAttempt.getInteger("count", 0); + if (attemptCount < 5) { + return MidmResponse.getResponse(410, "Email or password is wrong."); + } else { + DateTime nextTryAfter = (new DateTime(loginAttempt.getDate("attemptAt"))).plusMinutes(10); + loginAttempt.append("tryAfter", nextTryAfter.toDate()); + this.emailService.sendExceedLoginFailure(request, response, user, nextTryAfter.withZone(DateTimeZone.forTimeZone(timeZone)), userAgent.client(), remoteIp); + return MidmResponse.getResponse(424, String.format("Login failed more than %d times.", 5), loginAttempt); + } + } else { + if (attemptCount > 0) { + this.userService.updateLoginAttempt(user, true); + } + + boolean hasChanges = false; + if (eulaUuid != null) { + PolicyAgreement agreement = (PolicyAgreement)this.policyAgreementService.findById(PolicyAgreement.class, eulaUuid); + if (agreement != null) { + user.setEula(agreement); + hasChanges = true; + } + } + + boolean isApiUser = user.isApiUser(); + if (!bypassEula && this.settingsService.eulaEnabled() && !user.isSystemUser() && !user.isEulaAgreed()) { + return MidmResponse.getResponse(418, String.format("The user(%s) need the EULA aggreement.", user.getEmail())); + } else { + if (this.sessionManager.isOnline(user.getUuid())) { + if (!forceToLogout) { + User loggedUser = UserPrincipal.getUser(authentication); + if (loggedUser != null && loggedUser.getUuid().equals(user.getUuid())) { + return this.loginResponse(authentication, user, user.getSite(), !Strings.isNullOrEmpty(sessionId)); + } + + return MidmResponse.getResponse(414, String.format("The user(%s) is logged in already.", user.getEmail())); + } + + this.userService.deleteLoginToken(user); + this.sessionManager.logout(user); + } + + Site site = null; + SiteInfo siteInfo = null; + UUID lastSiteUuid = user.getLastSite(); + if (lastSiteUuid != null) { + site = this.siteService.findByUuid(lastSiteUuid); + siteInfo = user.getSiteInfo(lastSiteUuid); + if (site == null) { + user.removeSite(lastSiteUuid); + hasChanges = true; + } else if (site.getEnabled() && siteInfo != null && siteInfo.isEnabled()) { + if (siteInfo.isApiOnly() && sessionId != null && userAgent.isBrowser()) { + return MidmResponse.getResponse(425, String.format("The user(%s) is only for API access. It can't be accessed from the browser.", user.getEmail())); + } + + user.setSiteUuid(lastSiteUuid); + } else { + user.setLastSite((UUID)null); + user.setSiteUuid((UUID)null); + lastSiteUuid = null; + site = null; + siteInfo = null; + hasChanges = true; + } + } else { + user.setLastSite((UUID)null); + user.setSiteUuid((UUID)null); + hasChanges = true; + } + + if (siteInfo == null && user.getLastSite() != null) { + List sites = new ArrayList(user.getSites()); + if (!sites.isEmpty()) { + for(Iterator it = sites.iterator(); it.hasNext(); site = null) { + siteInfo = (SiteInfo)it.next(); + site = this.siteService.findByUuid(siteInfo.getSiteUuid()); + if (site == null) { + it.remove(); + user.setLastSite((UUID)null); + user.setSiteUuid((UUID)null); + hasChanges = true; + } else if (site.getEnabled() && siteInfo.isEnabled()) { + lastSiteUuid = siteInfo.getSiteUuid(); + user.setLastSite(lastSiteUuid); + user.setSiteUuid(lastSiteUuid); + hasChanges = true; + break; + } + + siteInfo = null; + } + } + } + + if (!remoteIp.equals(user.getProfile("ip"))) { + user.setProfile("ip", remoteIp); + hasChanges = true; + } + + if (!isApiUser) { + McResponse.setCookie(response, "locale", user.getLocale()); + } + + if (siteInfo == null && !user.isSystemUser()) { + return MidmResponse.getResponse(451, "No site available nor system administrator."); + } else { + authentication = this.userService.authorizeLogin(user); + if (!isApiUser) { + if (lastSiteUuid != null) { + McResponse.setCookie(response, "site.uuid", lastSiteUuid.toString()); + } + + if (timeZone != null && site != null && !site.hasTimeZone()) { + this.siteService.setSetting(site.getUuid(), "general.timeZone", timeZone.getID()); + } + + if (user.getSettingAsBoolean("keepSignIn") != keepSignIn) { + user.setSetting("keepSignIn", keepSignIn); + hasChanges = true; + } + + if (keepSignIn) { + Cookie cookie = new Cookie("user.token", ((UserToken)authentication.getCredentials()).getTokenUuid().toString()); + cookie.setPath("/"); + response.addCookie(cookie); + } + + if (hasChanges) { + this.userService.save(user); + } + } + + MidmLog log = new MidmLog(user, user.getUuid(), "activity", String.format("Logged in from %s in %s - %s", userAgent.agentFamily(), userAgent.osFamily(), remoteIp)); + log.setReference(userAgent, sessionId, remoteIp); + this.logService.save(log); + return this.loginResponse(authentication, user, site, !Strings.isNullOrEmpty(sessionId)); + } + } + } + } + } else { + return MidmResponse.getResponse(410, "No email or password defined."); + } + } + + @RequestMapping( + value = {"/logout"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + this.sessionManager.logout(user); + this.userService.deleteLoginToken(user); + SecurityContextHolder.getContext().setAuthentication((Authentication)null); + McResponse.setCookie(response, "user.token", (String)null); + this.logService.save(user, user.getUuid(), "activity", "Logged out."); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/register"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String register(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false,defaultValue = "") Set roles, @RequestBody User user) { + String email = user.getEmail(); + User existingUser = this.userService.findUserByEmail(email); + String password = user.getPassword(); + if (existingUser == null) { + if (Strings.isNullOrEmpty(email) || Strings.isNullOrEmpty(password)) { + return MidmResponse.getResponse(413, "Email or password not defined."); + } + + if (!McEmailUtils.isValid(user.getEmail())) { + return MidmResponse.getResponse(413, "Invalid email format."); + } + } else { + if (existingUser.isApiUser()) { + return MidmResponse.getResponse(425, "API only user can't be registerd to other site."); + } + + UUID groupUuid = user.getGroupUuid(); + user = existingUser; + existingUser.setGroupUuid(groupUuid); + } + + if (this.userService.hasUser()) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } + + if (siteUuid == null && Strings.isNullOrEmpty(siteId)) { + siteUuid = loggedUser.getSiteUuid(); + } + + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site != null) { + if (!loggedUser.canHandle(siteUuid, UserRole.USER_MANAGE_ROLES)) { + if (site.isChild()) { + UUID resellerUuid = site.getReseller().getUuid(); + if (!loggedUser.canHandle(resellerUuid, "SUPERVISOR")) { + return MidmResponse.getResponse(433, "No permission."); + } + + if (this.userService.countSupervisor(siteUuid) > 1L) { + return MidmResponse.getResponse(433, "No permission."); + } + } else { + if (!loggedUser.hasSystemRole("SYSTEM_ADMIN") && !loggedUser.hasSystemRole("SITE_MANAGER")) { + return MidmResponse.getResponse(433, "No permission."); + } + + if (this.userService.countSupervisor(siteUuid) > 1L) { + return MidmResponse.getResponse(433, "No permission."); + } + } + } + + user.addSite(siteUuid); + SiteInfo siteInfo = user.getSiteInfo(siteUuid); + if (!roles.isEmpty()) { + siteInfo.setRoles(roles); + } + + if (user.getGroupUuid() != null) { + UserGroup userGroup = this.userService.findUserGroup(user.getGroupUuid()); + if (userGroup != null) { + siteInfo.setGroupUuid(userGroup.getUuid()); + } + } + + user.setSite(site); + user.setLastSite(site.getUuid()); + } else if (!loggedUser.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getFailedResponse(); + } + } else { + user.addSystemRole("SYSTEM_ADMIN"); + } + + user.setActivated(); + User registeredUser = null; + if (existingUser == null) { + registeredUser = this.userService.register(request, response, user); + } else { + registeredUser = this.userService.save(user); + } + + if (registeredUser == null) { + return MidmResponse.getFailedResponse(); + } else { + this.deviceService.updateDeviceOwner(siteUuid, user, true); + return MidmResponse.getSucceedResponse((Object)registeredUser); + } + } + + @RequestMapping( + value = {"/updateProfile"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateProfile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestBody DbObject profile) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + loggedUser.updateProfile(profile); + UpdateResult result = this.userService.updateProfile(loggedUser); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"{siteModel}/register"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String registerToModelSite(HttpServletRequest request, HttpServletResponse response, @PathVariable("siteModel") String siteModel, @RequestBody User user) { + if (user != null && user.canRegister()) { + Site modelSite = this.siteService.findByIdName(siteModel); + if (modelSite == null) { + modelSite = new Site(); + modelSite.setIsReseller(true); + modelSite.setIdName(siteModel); + modelSite.setName(siteModel); + modelSite.setPlan(new DbObject("plan", "standard")); + modelSite = this.siteService.save(modelSite); + } + + Site site = this.siteService.findByIdName(user.getEmail()); + if (site == null) { + site = new Site(siteModel); + site.setReseller(modelSite); + site.setIdName(user.getEmail()); + site.setPlan(new DbObject("plan", "standard")); + String name = user.getName(); + if (Strings.isNullOrEmpty(name)) { + name = user.getEmail(); + } + + site.setName(name); + site.setEnabled(true); + site = this.siteService.save(site); + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.init(); + deviceProfile.setName(user.getName()); + deviceProfile.setSiteUuid(site.getUuid()); + deviceProfile.setWriterUuid(user.getUuid()); + deviceProfile.setWriter(user); + deviceProfile.setProfile("applyWhile", "sleeping", true); + deviceProfile.setProfile("updateVia", "both"); + deviceProfile.setProfile("repeatOption", "once"); + deviceProfile.setProfile("endsOption", "never"); + deviceProfile.setProfile("ends", (new DateTime()).toLocalDate().plusMonths(1).toDate()); + deviceProfile.setProfile("repeatEvery", "1"); + deviceProfile.setProfile("repeatPeriod", "day"); + deviceProfile.setProfile("timeOption", "allDay"); + deviceProfile.setEnabled(true); + deviceProfile.setIsGlobal(true); + Object startsOnDate = deviceProfile.getProfile("startsOn"); + if (startsOnDate == null) { + deviceProfile.setProfile("startsOn", (new DateTime(deviceProfile.getUpdated())).toLocalDate().toDate()); + } + + deviceProfile = this.profileService.save(deviceProfile); + this.logService.save((User)null, deviceProfile.getUuid(), "update", "Generated"); + UUID var14 = site.getUuid(); + User existingUser = this.userService.findUserByEmail(user.getEmail()); + if (existingUser != null) { + if (site != null) { + existingUser.addSite(var14); + if (!existingUser.isActivated()) { + existingUser.setActivated(); + } + + startsOnDate = existingUser.getSiteInfo(var14); + ((SiteInfo)startsOnDate).addRole("SUPERVISOR"); + this.userService.save(existingUser); + } + + return MidmResponse.getSucceedResponse((Object)existingUser); + } else { + user.setActivated(); + user.addSite(var14); + startsOnDate = user.getSiteInfo(var14); + ((SiteInfo)startsOnDate).addRole("SUPERVISOR"); + User registeredUser = this.userService.register(request, response, user); + return registeredUser == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse((Object)registeredUser); + } + } else { + return MidmResponse.getResponse(412, "The account is already registered."); + } + } else { + return MidmResponse.getResponse(410, "Email and password is necessory to register an user."); + } + } + + @RequestMapping( + value = {"/enable"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String enableUsers(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(name = "uuid") List uuids, @RequestParam boolean enabled) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (siteUuid == null) { + siteUuid = loggedUser.getSiteUuid(); + } + + if (uuids != null && !uuids.isEmpty()) { + Iterator it = uuids.iterator(); + + while(it.hasNext()) { + if (((UUID)it.next()).equals(loggedUser.getUuid())) { + it.remove(); + } + } + + this.userService.enableUsers(siteUuid, uuids, enabled); + uuids.forEach((uuid) -> { + User user = this.userService.findUserByUserUuid(uuid); + if (user != null && this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.logout(user); + } + + }); + } + + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/changeGroup"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String changeGroup(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false,defaultValue = "") Set userUuids, @RequestParam(required = false,defaultValue = "") Set emails, @RequestParam(required = false) UUID groupUuid, @RequestParam(required = false) String groupPath) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!loggedUser.hasSystemRole("SYSTEM_ADMIN") && !loggedUser.hasRole("SUPERVISOR") && !loggedUser.hasRole("USER_MANAGER")) { + return MidmResponse.getFailedResponse(); + } else { + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site == null) { + return MidmResponse.getFailedResponse(); + } else { + siteUuid = site.getUuid(); + UserGroup group = null; + if (groupUuid != null) { + group = this.userService.findUserGroup(groupUuid); + } + + if (group == null && !Strings.isNullOrEmpty(groupPath)) { + group = this.userService.findUserGroup(siteUuid, groupPath); + } + + if (group != null) { + groupUuid = group.getUuid(); + } + + long updatedCount = 0L; + if (userUuids != null && !userUuids.isEmpty()) { + updatedCount += this.userService.changeGroupByUuid(siteUuid, groupUuid, userUuids); + } + + if (emails != null && !emails.isEmpty()) { + updatedCount += this.userService.changeGroupByEmail(siteUuid, groupUuid, emails); + } + + return MidmResponse.getSucceedResponse((Object)updatedCount); + } + } + } + + @RequestMapping( + value = {"/activate"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String activate(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasRole("SUPERVISOR")) { + return MidmResponse.getFailedResponse(); + } else { + user = (User)McJsonUtils.toObject(request, User.class); + if (user != null && user.getUuid() != null) { + User registeredUser = this.userService.findUserByUserUuid(user.getUuid()); + if (registeredUser == null) { + return MidmResponse.getFailedResponse(); + } else { + this.userService.activate(user.getUuid()); + return MidmResponse.getSucceedResponse((Object)registeredUser); + } + } else { + return MidmResponse.getResponse(412, "User may not registered."); + } + } + } + + @RequestMapping( + value = {"/eula/agree"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String agreeEula(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String eula, @RequestParam(required = false) String email) { + User loggedUser = this.userService.findUserByEmail(email.trim()); + loggedUser.setEula(eula); + loggedUser = this.userService.save(loggedUser); + return MidmResponse.getSucceedResponse((Object)loggedUser); + } + + @RequestMapping( + value = {"/dashboardSettings"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String setDashboard(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List dashboard = (List)McJsonUtils.toObject(request, List.class); + user.setDashboardSettings(dashboard); + user = this.userService.save(user); + return MidmResponse.getSucceedResponse((Object)user); + } + } + + @RequestMapping( + value = {"/passwordConfirm"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String passwordConfirm(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String password) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + return this.userService.matchPassword(user, password) ? MidmResponse.getSucceedResponse((Object)user) : MidmResponse.getResponse(410, "Email or password is wrong."); + } + } + + @RequestMapping( + value = {"/getDashboardSettings"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getDashboard(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse(user.getDashboardSettings()); + } + + @RequestMapping( + value = {"/activate/{token}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + public String activate(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("token") String tokenString) { + User user = this.userService.activate(request, response, tokenString); + return "redirect:/?" + (user != null ? "activation_done" : "activation_failed"); + } + + @RequestMapping( + value = {"/requestResetPassword"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String requestResetPassword(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) String email) { + User user = Strings.isNullOrEmpty(email) ? (User)McJsonUtils.toObject(request, User.class) : new User(email); + if (user != null && !McStringUtils.isNullOrEmpty(user.getEmail())) { + user = this.userService.findUserByEmail(user.getEmail()); + if (user == null) { + return MidmResponse.getSucceedResponse(); + } else { + this.userService.requestResetPassword(request, response, user); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(410, "Request User must have email."); + } + } + + @RequestMapping( + value = {"/changePassword"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String changePassword(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) UUID tokenUuid, @RequestBody DbObject params) { + User loggedUser = UserPrincipal.getUser(authentication); + User user = this.userService.findUserByUserUuid(userUuid); + if (user == null) { + return MidmResponse.getResponse(410, "No user exists."); + } else { + String newPassword = params.getString("newPassword"); + if (Strings.isNullOrEmpty(newPassword)) { + return MidmResponse.getResponse(411, "No new password defined"); + } else { + if (tokenUuid != null) { + UserToken token = this.userService.findToken(tokenUuid); + if (token == null) { + return MidmResponse.getResponse(463, "Invalid token"); + } + + if (token.isExpired()) { + this.userService.delete(token); + return MidmResponse.getResponse(462, "Expired token"); + } + + if (!token.getUserUuid().equals(userUuid)) { + return MidmResponse.getResponse(463, "Not match user"); + } + + this.sessionManager.logout(user); + this.logService.save(user, user.getUuid(), "activity", "Logged out from password reset."); + this.userService.deleteLoginToken(user); + SecurityContextHolder.getContext().setAuthentication((Authentication)null); + this.userService.changePassword(user, newPassword); + } else { + String curPassword = params.getString("curPassword"); + if (Strings.isNullOrEmpty(curPassword)) { + return MidmResponse.getResponse(411, "No currernt password defined"); + } + + if (loggedUser == null) { + return MidmResponse.getFailedResponse(); + } + + if (!loggedUser.getUuid().equals(user.getUuid())) { + return MidmResponse.getFailedResponse(); + } + + if (!this.userService.matchPassword(user, curPassword)) { + return MidmResponse.getResponse(411, "Password not matches"); + } + + this.userService.changePassword(user, newPassword); + user = this.userService.findUserByUserUuid(userUuid); + this.userService.authorizeLogin(user); + } + + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/saveLastPage"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveLastPage(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String curPage) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean result = this.userService.setLastPage(loggedUser, curPage); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"/changeLocale"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String changeLocale(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String locale) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean result = this.userService.changeLocale(loggedUser, locale); + McResponse.setCookie(response, "locale", locale); + return MidmResponse.getSucceedResponse((Object)result); + } + } + + @RequestMapping( + value = {"/settings"}, + method = {RequestMethod.POST}, + produces = {"text/plain"} + ) + @ResponseBody + public String changeSettings(HttpServletRequest request, Authentication authentication, @RequestParam String key, @RequestParam String value, @RequestHeader(value = "Authorization",required = false) String accessToken) { + if (Strings.isNullOrEmpty(key)) { + return MidmResponse.getFailedResponse(); + } else { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + loggedUser.setSetting(key, value); + this.userService.setSetting(loggedUser, key, value); + return MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/settings/get"}, + method = {RequestMethod.GET}, + produces = {"text/plain"} + ) + @ResponseBody + public String getSettings(HttpServletRequest request, Authentication authentication, @RequestParam String key, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Object value = loggedUser.getSetting(key); + return MidmResponse.getSucceedResponse(value); + } + } + + @RequestMapping( + value = {"/settings/get/page"}, + method = {RequestMethod.GET}, + produces = {"text/plain"} + ) + @ResponseBody + public String getPageSettings(HttpServletRequest request, Authentication authentication, @RequestParam String pageUrl, @RequestHeader(value = "Authorization",required = false) String accessToken) { + if (Strings.isNullOrEmpty(pageUrl)) { + return MidmResponse.getFailedResponse(); + } else { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Object value = loggedUser.getPageSettings(pageUrl); + return value == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse(value); + } + } + } + + @RequestMapping( + value = {"/site/page/settings"}, + method = {RequestMethod.GET}, + produces = {"text/plain"} + ) + @ResponseBody + public String getSitePageSettings(HttpServletRequest request, Authentication authentication, @RequestParam String pageUrl, @RequestHeader(value = "Authorization",required = false) String accessToken) { + if (Strings.isNullOrEmpty(pageUrl)) { + return MidmResponse.getFailedResponse(); + } else { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + SiteInfo siteInfo = loggedUser.getSiteInfo(loggedUser.getSiteUuid()); + DbObject settings = siteInfo == null ? null : siteInfo.getPageSetting(pageUrl); + return settings == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse((Object)settings); + } + } + } + + @RequestMapping( + value = {"/settings/set/page"}, + method = {RequestMethod.POST}, + produces = {"text/plain"} + ) + @ResponseBody + public String setPageSettings(HttpServletRequest request, Authentication authentication, @RequestParam String pageUrl, @RequestParam String key, @RequestParam String value, @RequestHeader(value = "Authorization",required = false) String accessToken) { + if (Strings.isNullOrEmpty(key)) { + return MidmResponse.getFailedResponse(); + } else { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + loggedUser.setPageSetting(pageUrl, key, value); + this.userService.setPageSetting(loggedUser, pageUrl, key, value); + return value == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse(); + } + } + } + + @RequestMapping( + value = {"/exists"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String exists(HttpServletRequest request, Principal principal, @RequestParam(required = false) String siteModel, @RequestParam String email) { + User user = this.userService.findUserByEmail(email); + if (user == null) { + return MidmResponse.getSucceedResponse((Object)false); + } else if (!Strings.isNullOrEmpty(siteModel)) { + Iterator it = user.getSites().iterator(); + boolean hasChanges = false; + + while(it.hasNext()) { + SiteInfo siteInfo = (SiteInfo)it.next(); + Site site = this.siteService.findByUuid(siteInfo.getSiteUuid()); + if (site == null) { + it.remove(); + hasChanges = true; + } else if (siteModel.equals(site.getModel())) { + return MidmResponse.getSucceedResponse((Object)true); + } + } + + if (hasChanges) { + this.userService.save(user); + } + + return MidmResponse.getSucceedResponse((Object)false); + } else { + return MidmResponse.getSucceedResponse((Object)true); + } + } + + @RequestMapping( + value = {"/verify"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String verify(HttpServletRequest request, Principal principal, @RequestParam String email, @RequestParam(required = false) String password) { + if (Strings.isNullOrEmpty(password)) { + return MidmResponse.getFailedResponse(); + } else { + User user = this.userService.findUserByEmail(email); + return user == null ? MidmResponse.getFailedResponse() : MidmResponse.getSucceedResponse((Object)this.userService.matchPassword(user, password)); + } + } + + @RequestMapping( + value = {"/sites"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findSites(HttpServletRequest request, Principal principal, @RequestParam String email, @RequestParam(required = false) String password, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + try { + email = URLDecoder.decode(email, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException var13) { + } + + if (Strings.isNullOrEmpty(password)) { + return MidmResponse.getFailedResponse(); + } + + user = this.userService.findUserByEmail(email); + if (user == null || !this.userService.matchPassword(user, password)) { + return MidmResponse.getResponse(410, "Email or password is wrong."); + } + } + + List sites = user.getSites(); + if (sites != null && !sites.isEmpty()) { + List sitesAvailable = new ArrayList(); + + for(SiteInfo siteInfo : sites) { + Site site = this.siteService.findByUuid(siteInfo.getSiteUuid()); + if (site != null && site.getEnabled()) { + sitesAvailable.add(site); + } + } + + if (sitesAvailable.size() == 0) { + return MidmResponse.getResponse(451, "No site available."); + } else { + return MidmResponse.getSucceedResponse(sitesAvailable); + } + } else { + return MidmResponse.getResponse(451, "No site available."); + } + } + + @RequestMapping( + value = {"/site/settings"}, + method = {RequestMethod.POST}, + produces = {"text/plain"} + ) + @ResponseBody + public String changeSiteSettings(HttpServletRequest request, Authentication authentication, @RequestParam String key, @RequestParam String value, @RequestHeader(value = "Authorization",required = false) String accessToken) { + if (Strings.isNullOrEmpty(key)) { + return MidmResponse.getFailedResponse(); + } else { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + boolean updated = this.userService.setSiteSetting(loggedUser, key, value); + return updated ? MidmResponse.getSucceedResponse((Object)updated) : MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/site/settings/get"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getSiteSettings(HttpServletRequest request, Authentication authentication, @RequestParam String key, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + SiteInfo siteInfo = loggedUser.getSiteInfo(loggedUser.getSiteUuid()); + if (siteInfo != null) { + Object value = siteInfo.getSetting(key); + return MidmResponse.getSucceedResponse(value); + } else { + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/findBy"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findBy(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID uuid, @RequestParam(required = false) String email, @RequestParam(required = false) String password) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + User user = this.userService.findUserByUserUuid(uuid); + if (user == null && McStringUtils.isValid(email)) { + user = this.userService.findUserByEmail(email); + if (!Strings.isNullOrEmpty(password) && !this.userService.matchPassword(user, password)) { + user = null; + } + } + + if (user == null) { + return MidmResponse.getFailedResponse(); + } else { + UUID siteUuid = loggedUser.getSiteUuid(); + if (!loggedUser.isSystemUser() && !user.isBelongedToSite(siteUuid)) { + return MidmResponse.getResponse(433, "No permission."); + } else { + user.setSiteInfo(user.getSiteInfo(siteUuid)); + user.setMultiSiteUser(); + user.setSites((List)null); + user.setPassword((String)null); + return MidmResponse.getSucceedResponse((Object)user); + } + } + } + } + + @RequestMapping( + value = {"/findByAccessToken"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findByAccessToken(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse((Object)user); + } + + @RequestMapping( + value = {"/findByEmail"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findByEmail(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam String email, @RequestParam(required = false) String[] fields) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!loggedUser.isBelongedToSite(loggedUser.getSiteUuid()) && !loggedUser.isSystemUser()) { + return MidmResponse.getResponse(433, "No permission."); + } else { + User user = this.userService.findUserByEmail(email, fields); + if (user != null) { + user.setMultiSiteUser(); + user.setSiteInfo(user.getSiteInfo(siteUuid)); + user.setSites((List)null); + user.setSettings((DbObject)null); + if (siteUuid == null) { + user.setSiteUuid((UUID)null); + } + + return MidmResponse.getSucceedResponse((Object)user); + } else { + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) String direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasRole(siteUuid, "SUPERVISOR") && !user.hasRole(siteUuid, "USER_MANAGER")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.userService.findUsers(siteUuid, filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/supervisors"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findSupervisors(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = true) UUID siteUuid, @RequestParam(required = false) String filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) String direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (!user.hasRole(siteUuid, "SUPERVISOR") && !user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SITE_MANAGER")) { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(451, "No site available."); + } + + if (!site.isChild() || site.getReseller() != null && !user.hasRole(site.getReseller().getUuid(), "SUPERVISOR")) { + return MidmResponse.getResponse(433, "No permission."); + } + } + + Page pageResult = this.userService.findSupervisors(siteUuid, filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/count"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String count(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse((Object)this.userService.getUserCount(user.getSiteUuid())); + } + + @RequestMapping( + value = {"/systemRoles/{command}/{role}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String addOrDeleteSystemRole(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String command, @PathVariable String role, @RequestParam(name = "uuid",defaultValue = "") List uuids) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser != null && loggedUser.hasSystemRole("SYSTEM_ADMIN")) { + UpdateResult result = this.userService.updateSystemRoles(command, role, uuids); + return MidmResponse.getSucceedResponse((Object)result); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/saveRoles", "/updateRoles"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveRoles(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) String email, @RequestParam(required = false,defaultValue = "") Set roles, @RequestParam(required = false) Boolean apiOnly) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site == null) { + return MidmResponse.getResponse(451, "Not authorized."); + } else { + siteUuid = site.getUuid(); + if (!loggedUser.canHandle(siteUuid, UserRole.USER_MANAGE_ROLES)) { + if (site.isChild()) { + UUID resellerUuid = site.getReseller().getUuid(); + if (!loggedUser.canHandle(resellerUuid, "SUPERVISOR")) { + return MidmResponse.getResponse(433, "No permission."); + } + + if (this.userService.findSupervisors(siteUuid).size() > 1) { + return MidmResponse.getResponse(433, "No permission."); + } + } else { + if (!loggedUser.hasSystemRole("SYSTEM_ADMIN") && !loggedUser.hasSystemRole("SITE_MANAGER")) { + return MidmResponse.getResponse(433, "No permission."); + } + + if (this.userService.countSupervisor(siteUuid) > 1L) { + return MidmResponse.getResponse(433, "No permission."); + } + } + } + + if (loggedUser.getUuid().equals(userUuid) && siteUuid.equals(loggedUser.getSiteUuid())) { + return MidmResponse.getResponse(415, "A user can't update his role."); + } else { + User user = this.userService.findUser(userUuid, email); + if (user == null) { + return MidmResponse.getResponse(452, "User not exists."); + } else { + if (user.getSites().size() > 1) { + apiOnly = false; + } + + if (roles.contains("SUPERVISOR")) { + roles.clear(); + roles.add("SUPERVISOR"); + } + + if (user.isBelongedToSite(siteUuid)) { + this.userService.updateRoles(user, siteUuid, roles, apiOnly); + } else { + if (user.isApiUser()) { + return MidmResponse.getResponse(425, "API only user can't belonged to other site."); + } + + SiteInfo siteInfo = user.addSite(siteUuid); + siteInfo.setRoles(roles); + if (apiOnly != null) { + siteInfo.setApiOnly(apiOnly); + } + + this.userService.addSite(user, siteInfo); + if (loggedUser.getUuid().equals(userUuid)) { + this.userService.updateAuthorizedUser(user); + } + } + + if (!loggedUser.getUuid().equals(user.getUuid()) && this.sessionManager.isOnline(user.getUuid())) { + this.sessionManager.logout(user); + } + + return MidmResponse.getSucceedResponse((Object)user); + } + } + } + } + } + + @RequestMapping( + value = {"/switchSite"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String switchSite(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String curPage) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + User user = this.userService.findUserByUserUuid(loggedUser.getUuid()); + if (user == null) { + return MidmResponse.getFailedResponse(); + } else { + Site site = null; + if (siteUuid != null) { + if (user.getSiteUuid() != null && user.getSiteUuid().equals(siteUuid)) { + return MidmResponse.getResponse(455, "Same site. no need to switch."); + } + + site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(450, "Site not found"); + } + + SiteInfo siteInfo = user.getSiteInfo(siteUuid); + if (siteInfo == null) { + return MidmResponse.getResponse(452, "Not site user"); + } + + if (!siteInfo.isEnabled()) { + return MidmResponse.getResponse(453, "Disabled user"); + } + + user.setSiteUuid(siteUuid); + user.setLastSite(siteUuid); + McResponse.setCookie(response, "site.uuid", siteUuid.toString()); + } else { + user.setSiteUuid((UUID)null); + user.setLastSite((UUID)null); + } + + if (this.userService.switchSite(user.getUuid(), siteUuid)) { + authentication = this.userService.authorizeLogin(user); + } + + return this.loginResponse(authentication, user, site, true); + } + } + } + + private String loginResponse(Authentication authentication, User user, Site site, boolean includeExtra) { + UserToken token = (UserToken)authentication.getCredentials(); + JsonObject jData = new JsonObject(); + jData.addProperty("accessToken", token.getAccessToken()); + if (includeExtra) { + jData.addProperty("lastPage", user.getLastPage()); + } + + jData.addProperty("siteModel", site != null ? site.getModel() : "none"); + return MidmResponse.getSucceedResponse((Object)jData); + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteSite(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) String email) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site == null) { + return MidmResponse.getResponse(451, "Not authorized."); + } else { + siteUuid = site.getUuid(); + User user = this.userService.findUserByUserUuid(userUuid); + if (user == null) { + return MidmResponse.getResponse(410, "No user exists."); + } else if (!user.isBelongedToSite(site.getUuid())) { + return MidmResponse.getResponse(451, "Not belonged to the site."); + } else if (loggedUser.getUuid().equals(user.getUuid())) { + return MidmResponse.getResponse(451, "Not belonged to the site."); + } else if (!loggedUser.canHandle(siteUuid, UserRole.USER_MANAGE_ROLES)) { + return MidmResponse.getResponse(415, "A user can't remove himself."); + } else { + UpdateResult result = this.userService.deleteSite(user, siteUuid); + return result.getModifiedCount() > 0L ? MidmResponse.getSucceedResponse((Object)"The site has been removed from the user.") : MidmResponse.getResponse(421, "Not removed from site."); + } + } + } + } + + @RequestMapping( + value = {"/info"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String userInfo(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + return user != null ? MidmResponse.getSucceedResponse((Object)user) : MidmResponse.getResponse(415, "Not authorized."); + } + + @RequestMapping( + value = {"/token/renew"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String renewToken(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null) { + UserToken token = this.userService.findToken(user, 'L'); + if (token != null) { + token.renew(); + this.userService.save(token); + return MidmResponse.getResponse(token); + } + } + + return MidmResponse.getResponse(415, "Not authorized."); + } + + @RequestMapping( + value = {"/devices"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String devices(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false,defaultValue = "profile.hardware_info.serial_no") String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Page pageResult = this.deviceService.findDevices(user.getSiteUuid(), filter, page, size, sortBy, direction, false, (Integer)null); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/profile/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, Authentication authentication, @RequestParam(required = false) UUID userUuid, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + if (userUuid != null) { + user = this.userService.findUserByUserUuid(userUuid); + } + + if (user == null) { + return MidmResponse.getFailedResponse(); + } else { + userUuid = user.getUuid(); + String profilePath = this.fileService.getUserProfilePath(userUuid); + McFile targetFile = new McFile(profilePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + try { + BufferedImage image = this.fileService.getProfileImage(file); + ImageIO.write(image, "jpg", targetFile); + return MidmResponse.getSucceedResponse((Object)user); + } catch (IOException e) { + e.printStackTrace(); + return MidmResponse.getFailedResponse(); + } + } + } + } + + @RequestMapping( + value = {"upload/list"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String uploadUserList(HttpServletRequest request, Authentication authentication, @RequestParam("file") MultipartFile file, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + String fileName = file.getOriginalFilename(); + String fileType = file.getContentType(); + + try { + List returnValues = null; + if (!fileName.endsWith(".xls") && !fileType.endsWith("excel") && !fileType.endsWith("xls")) { + if (fileName.endsWith(".xlsx") || fileType.endsWith(".xlsx") || fileType.equals(McFile.CONTENT_TYPE_XLSX)) { + returnValues = this.parseXlsx(user, file.getInputStream(), user.getSiteUuid()); + } + } else { + returnValues = this.parseXls(user, file.getInputStream(), user.getSiteUuid()); + } + + if (returnValues != null && returnValues.get(0) instanceof User) { + this.userService.saveUsers(returnValues); + return MidmResponse.getSucceedResponse(returnValues); + } else { + return MidmResponse.getResponse(404, "Parsing error", returnValues); + } + } catch (IOException e) { + e.printStackTrace(); + return MidmResponse.getFailedResponse(); + } + } + } + + private User parseRow(User loggedUser, Row row, UUID siteUuid) throws MidmParseException { + String sheetName = row.getSheet().getSheetName(); + Iterator cells = row.cellIterator(); + User user = null; + User existingUser = null; + if (row.getRowNum() == 0) { + this.emailColumnIndex = -1; + this.columns = new HashMap(); + + while(cells.hasNext()) { + Cell cell = (Cell)cells.next(); + String value = cell.getStringCellValue(); + if (McStringUtils.isValid(value)) { + this.columns.put(cell.getColumnIndex(), USER_PROPERTY.get(value)); + USER_PROPERTY property = (USER_PROPERTY)this.columns.get(cell.getColumnIndex()); + if (property == USER_PROPERTY.email || property == USER_PROPERTY.email_addr || property == USER_PROPERTY.email_address || property == USER_PROPERTY.mail) { + this.emailColumnIndex = this.columns.size() - 1; + } + } + } + + if (this.emailColumnIndex < 0) { + throw UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), "No email column found."); + } else { + return null; + } + } else if (ExcelRow.isEmpty(row)) { + return null; + } else { + Cell emailCell = row.getCell(this.emailColumnIndex); + if (emailCell != null && !ExcelCell.isEmpty(emailCell)) { + String emailValue = emailCell.getStringCellValue(); + emailValue = emailValue.toLowerCase().trim(); + if (Strings.isNullOrEmpty(emailValue)) { + throw UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), "No email defined."); + } else if (!McEmailUtils.isValid(emailValue)) { + throw UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), "Bad Email format-" + emailValue); + } else { + existingUser = this.userService.findUserByEmail(emailValue); + if (existingUser != null) { + user = existingUser; + if (existingUser.isBelongedToSite(siteUuid)) { + throw UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), String.format("Existing user(%s) in this site.", emailValue)); + } + + if (existingUser.isApiUser()) { + throw UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), String.format("API only user(%s) can't be belonged to this site.", emailValue)); + } + + existingUser.addSite(siteUuid); + } else { + user = new User(); + user.setEmail(emailValue); + user.addSite(siteUuid); + user.init(); + } + + while(cells.hasNext()) { + Cell cell = (Cell)cells.next(); + CellType celltype = cell.getCellType(); + USER_PROPERTY property = (USER_PROPERTY)this.columns.get(cell.getColumnIndex()); + if (property != null && property != USER_PROPERTY.unknown && !ExcelCell.isEmpty(cell)) { + if (celltype != CellType.STRING) { + throw UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), property + " must be text."); + } + + String value = cell.getStringCellValue(); + if (!McStringUtils.isNullOrEmpty(value)) { + switch (property) { + case role: + case roles: + if (!Strings.isNullOrEmpty(value)) { + for(String role : value.split(",")) { + role = role.trim().toUpperCase(); + if (role.startsWith("SUPER") && loggedUser.hasRole("SUPERVISOR")) { + user.addRoleToSite("SUPERVISOR", siteUuid); + } else if (role.startsWith("USER")) { + user.addRoleToSite("USER_MANAGER", siteUuid); + } else if (role.startsWith("PROFILE")) { + user.addRoleToSite("PROFILE_MANAGER", siteUuid); + } else if (role.startsWith("DEVICE")) { + user.addRoleToSite("DEVICE_MANAGER", siteUuid); + } + } + } + break; + case password: + case pwd: + if (user.getPassword() == null) { + if (!user.setPassword(value)) { + throw UserApi.MidmParseException.genException(405, sheetName, row.getRowNum(), "Bad password format."); + } + + user.encodePassword(this.passwordEncoder); + } + break; + case name: + if (existingUser == null) { + user.setName(value); + } + break; + case title: + case position: + if (existingUser == null) { + user.setProfile("title", value); + } + break; + case tel: + case phone: + case telephone: + if (existingUser == null) { + user.setProfile("phone", value); + } + break; + case mobile: + case mobilephone: + case mobile_phone: + if (existingUser == null) { + user.setProfile("mobile", value); + } + break; + case group: + UserGroup userGroup = this.userService.findUserGroup(siteUuid, value); + if (userGroup == null) { + throw UserApi.MidmParseException.genException(405, sheetName, row.getRowNum(), "No group: " + value); + } + + user.setUserGroup(userGroup); + } + } + } + } + + if (existingUser == null && Strings.isNullOrEmpty(user.getPassword())) { + throw UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), "Password is necessory to register an user"); + } else { + return user; + } + } + } else { + throw UserApi.MidmParseException.genException(401, sheetName, row.getRowNum(), "No email found."); + } + } + } + + private List parseSheets(User loggedUser, Iterator sheets, UUID siteUuid) { + List users = new ArrayList(); + List exceptions = new ArrayList(); + + while(sheets.hasNext()) { + Sheet sheet = (Sheet)sheets.next(); + String sheetName = sheet.getSheetName(); + Iterator rows = sheet.rowIterator(); + + while(rows.hasNext()) { + try { + Row row = (Row)rows.next(); + if (!ExcelRow.isEmpty(row)) { + User user = this.parseRow(loggedUser, row, siteUuid); + if (row.getRowNum() > 0) { + if (user == null) { + exceptions.add(UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), "It may contains abnormal user information.")); + } else if (users.size() == 0) { + users.add(user); + } else { + for(User userItem : users) { + if (userItem.getEmail().equals(user.getEmail())) { + exceptions.add(UserApi.MidmParseException.genException(400, sheetName, row.getRowNum(), "Duplicated user-" + userItem.getEmail())); + break; + } + } + + users.add(user); + } + } + } + } catch (MidmParseException e) { + exceptions.add(e); + } + } + } + + if (exceptions.isEmpty()) { + return users; + } else { + return exceptions; + } + } + + private List parseXls(User loggedUser, InputStream is, UUID siteUuid) { + List returnValues = null; + + try { + HSSFWorkbook wb = new HSSFWorkbook(is); + returnValues = this.parseSheets(loggedUser, wb.sheetIterator(), siteUuid); + this.parseSheets(loggedUser, wb.sheetIterator(), siteUuid); + wb.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + return returnValues; + } + + private List parseXlsx(User loggedUser, InputStream is, UUID siteUuid) { + List returnValues = null; + + try { + XSSFWorkbook wb = new XSSFWorkbook(is); + returnValues = this.parseSheets(loggedUser, wb.sheetIterator(), siteUuid); + this.parseSheets(loggedUser, wb.sheetIterator(), siteUuid); + wb.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + return returnValues; + } + + private static class MidmParseException extends Exception { + private static final long serialVersionUID = 1L; + + public MidmParseException(int code, String message) { + super(message); + } + + public static MidmParseException genException(int code, String sheetName, int rowNum, String reason) { + String message = String.format("%s:%04d %s", sheetName, rowNum, reason); + return new MidmParseException(code, message); + } + } +} diff --git a/src/main/java/com/midm/webservice/org/UserGroupApi.java b/src/main/java/com/midm/webservice/org/UserGroupApi.java new file mode 100644 index 0000000..3c39951 --- /dev/null +++ b/src/main/java/com/midm/webservice/org/UserGroupApi.java @@ -0,0 +1,122 @@ +package com.midm.webservice.org; + +import com.google.common.base.Strings; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.model.org.UserGroup; +import com.midm.model.org.UserRole; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/user/group"}) +public class UserGroupApi { + @Autowired + private UserService userService; + @Autowired + private SiteService siteService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestBody UserGroup group) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site == null) { + return MidmResponse.getResponse(451, "Not authorized."); + } else { + siteUuid = site.getUuid(); + if (!loggedUser.canHandle(siteUuid, UserRole.USER_MANAGE_ROLES)) { + return MidmResponse.getResponse(433, "No permission."); + } else if (group != null && !Strings.isNullOrEmpty(group.getName())) { + if (group.getUuid() == null) { + group.init(); + } + + group.setSiteUuid(siteUuid); + group = this.userService.save(group); + return MidmResponse.getSucceedResponse((Object)group); + } else { + return MidmResponse.getResponse(400, "No group defined."); + } + } + } + } + + @RequestMapping( + value = {"/all"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site == null) { + return MidmResponse.getResponse(451, "Not authorized."); + } else { + siteUuid = site.getUuid(); + List userGroups = this.userService.findAllUserGroups(siteUuid); + return MidmResponse.getSucceedResponse(userGroups); + } + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID groupUuid, @RequestParam(required = false) String groupPath) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.find(loggedUser, siteUuid, siteId); + if (site == null) { + return MidmResponse.getResponse(451, "Not authorized."); + } else { + siteUuid = site.getUuid(); + UserGroup userGroup = null; + if (groupUuid != null) { + userGroup = this.userService.findUserGroup(groupUuid); + } + + if (userGroup == null && !Strings.isNullOrEmpty(groupPath)) { + userGroup = this.userService.findUserGroup(siteUuid, groupPath); + } + + if (userGroup != null && userGroup.getSiteUuid().equals(siteUuid)) { + this.userService.delete(userGroup); + return MidmResponse.getSucceedResponse((Object)userGroup); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + } + } +} diff --git a/src/main/java/com/midm/webservice/ota/OtaService.java b/src/main/java/com/midm/webservice/ota/OtaService.java new file mode 100644 index 0000000..30754a5 --- /dev/null +++ b/src/main/java/com/midm/webservice/ota/OtaService.java @@ -0,0 +1,88 @@ +package com.midm.webservice.ota; + +import com.google.common.base.Strings; +import com.midm.model.file.OtaFile; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.security.UserPrincipal; +import com.midm.service.file.FileService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.io.McResource; +import com.mitac.cell.security.McBase64; +import java.util.List; +import java.util.UUID; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class OtaService { + private static final String BASIC_AUTH = "Basic"; + @Autowired + private ServletContext servletContext; + @Autowired + private FileService fileService; + + @RequestMapping( + value = {"/otas"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String credentials, @RequestParam(required = true) String productId, @RequestParam(required = false) Long buildDate, @RequestParam(required = false) String deviceId, @RequestParam(required = false) String skuId) { + if (!Strings.isNullOrEmpty(credentials) && credentials.startsWith("Basic")) { + credentials = McBase64.fromBase64ToString(credentials.substring("Basic".length() + 1)); + int indexSeparator = credentials.indexOf(58); + if (indexSeparator < 0) { + return MidmResponse.getResponse(415, "Wrong Auth format"); + } else { + String otaCert = credentials.substring(indexSeparator + 1); + List otas = this.fileService.findAvailableOtas(productId, buildDate, otaCert); + return MidmResponse.getSucceedResponse(otas); + } + } else { + return MidmResponse.getResponse(415, "No Auth header defined"); + } + } + + @RequestMapping( + value = {"/otas/{fileUuid}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getFile(HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String credentials, @PathVariable UUID fileUuid, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + boolean allowed = false; + if (user == null) { + if (Strings.isNullOrEmpty(credentials) || !credentials.startsWith("Basic")) { + return; + } + + credentials = McBase64.fromBase64ToString(credentials.substring("Basic".length() + 1)); + int indexSeparator = credentials.indexOf(58); + if (indexSeparator < 0) { + return; + } + + String otaCert = credentials.substring(indexSeparator + 1); + if (this.fileService.matchOta(fileUuid, otaCert)) { + allowed = true; + } + } else { + allowed = true; + } + + if (allowed) { + String filePath = this.fileService.getFilePath((UUID)null, "ota", (UUID)fileUuid); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } +} diff --git a/src/main/java/com/midm/webservice/stat/StatApi.java b/src/main/java/com/midm/webservice/stat/StatApi.java new file mode 100644 index 0000000..9c83354 --- /dev/null +++ b/src/main/java/com/midm/webservice/stat/StatApi.java @@ -0,0 +1,241 @@ +package com.midm.webservice.stat; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.model.device.DeviceProfile; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.security.UserPrincipal; +import com.midm.service.device.DeviceService; +import com.midm.service.device.ProfileService; +import com.midm.service.org.SiteLicenseService; +import com.midm.service.org.SiteService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.LicenseService; +import com.mitac.cell.utils.McJsonUtils; +import java.security.Principal; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/stat"}) +public class StatApi { + @Autowired + private SiteService siteService; + @Autowired + private DeviceService deviceService; + @Autowired + private LicenseService licenseService; + @Autowired + private SiteLicenseService siteLicenseService; + @Autowired + private ProfileService profileService; + @Autowired + private HostLicenseService hostLicenseService; + + @RequestMapping( + value = {"/dbquery"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String get(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestParam(required = false) String db, @RequestParam(required = false) String[] fields, @RequestParam(required = false) String filter, @RequestParam(required = false) UUID[] uuids, @RequestParam(required = false) UUID uuid, @RequestParam(name = "profileUuid",required = false) String profile) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + JsonElement result = null; + UUID siteUuid = user.getSiteUuid(); + switch (DeviceService.KEY.get(db)) { + case device: + result = this.getDeviceStat(siteUuid, fields, filter); + break; + case profile: + result = this.getProfileStat(siteUuid, profile); + break; + case site: + return MidmResponse.getSucceedResponse(this.getSiteStat(user.getSite())); + case site_license: + return MidmResponse.getSucceedResponse(this.getLicenseStat((Site)null, uuid)); + case license: + return MidmResponse.getSucceedResponse(this.getLicenseStat(user.getSite(), (UUID)null)); + } + + return result != null ? MidmResponse.getSucceedResponse((Object)result) : MidmResponse.getFailedResponse(); + } + } + + @RequestMapping( + value = {"/getProfile"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getProfile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestParam(required = false) UUID uuid, @RequestParam(required = false) JsonObject filter) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + List deviceProfiles = this.profileService.findProfiles(filter, (String)null, (Sort.Direction)null); + return MidmResponse.getSucceedResponse(deviceProfiles); + } + } + + @RequestMapping( + value = {"/siteQuery"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String siteQuery(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasRole("SUPERVISOR") && !user.hasSystemRole()) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.siteService.findAdminState(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/totalState"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String totalState(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + return !user.hasSystemRole() ? MidmResponse.getResponse(433, "No permission.") : MidmResponse.getSucceedResponse((Object)this.siteService.totalState()); + } + } + + @RequestMapping( + value = {"/totalLicenseAmount"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String totalLicenseAmount(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + return !user.hasSystemRole("SYSTEM_ADMIN") ? MidmResponse.getResponse(433, "No permission.") : MidmResponse.getSucceedResponse(this.siteService.getTotalLicenseCount()); + } + } + + @RequestMapping( + value = {"/childState"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String childState(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page childSiteStat = this.siteService.childState(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(childSiteStat); + } + } + + private JsonObject getDeviceStat(UUID siteUuid, String[] fields, String filter) { + JsonObject jResult = new JsonObject(); + long total = this.deviceService.getDeviceTotal(siteUuid, filter); + jResult.addProperty("total", total); + + for(String field : fields) { + long value = -1L; + JsonObject jModelType = new JsonObject(); + switch (DeviceService.KEY.get(field)) { + case enrolled: + case disabled: + case license_expired: + case inactive: + case online: + value = this.deviceService.getDeviceStat(siteUuid, filter, field); + break; + case model: + case model_online: + case os: + case carrier: + case battery_condition: + jModelType = this.deviceService.getDeviceStateGroup(siteUuid, filter, field); + } + + if (value >= 0L) { + jResult.addProperty(field, value); + } + + if (jModelType != null && jModelType.size() > 0) { + jResult.add(field, jModelType); + } + } + + return jResult.size() > 0 ? jResult : null; + } + + private List getLicenseStat(Site site, UUID siteUuid) { + if (this.hostLicenseService.isStandalone()) { + return null; + } else { + List licenseModels; + if (siteUuid != null) { + Site childSite = this.siteService.findByUuid(siteUuid); + licenseModels = this.siteLicenseService.getLicenseModels(childSite, childSite.getPlanName()); + } else if (site == null) { + licenseModels = this.licenseService.getAllModels(); + } else { + licenseModels = this.siteLicenseService.getLicenseModels(site, site.getPlanName()); + } + + return licenseModels; + } + } + + private List getSiteStat(Site site) { + List siteList = this.siteService.findAll(site, "midm", (String)null, (String)null, true); + return siteList; + } + + private JsonArray getProfileStat(UUID siteUuid, String profile) { + DeviceProfile deviceProfile; + try { + UUID profileUuid = UUID.fromString(profile); + deviceProfile = this.profileService.find(profileUuid, false); + } catch (Exception var5) { + deviceProfile = this.profileService.findBySiteUuidAndProfileName(siteUuid, profile); + } + + if (deviceProfile == null) { + return new JsonArray(); + } else { + JsonArray jResult = new JsonArray(); + jResult.add(McJsonUtils.toJsonElement(this.profileService.getProfileState(deviceProfile))); + return jResult; + } + } +} diff --git a/src/main/java/com/midm/webservice/store/KeyStoreApi.java b/src/main/java/com/midm/webservice/store/KeyStoreApi.java new file mode 100644 index 0000000..650374c --- /dev/null +++ b/src/main/java/com/midm/webservice/store/KeyStoreApi.java @@ -0,0 +1,168 @@ +package com.midm.webservice.store; + +import com.google.gson.JsonObject; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.store.KeyStore; +import com.midm.security.UserPrincipal; +import com.midm.service.org.UserService; +import com.midm.service.store.KeyStoreService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.io.McResource; +import java.io.IOException; +import java.security.Principal; +import java.util.List; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"api/store/key"}) +public class KeyStoreApi { + @Autowired + private UserService userService; + @Autowired + private KeyStoreService keyStoreService; + @Autowired + private ServletContext servletContext; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveOta(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, KeyStore keyStore) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + keyStore = this.keyStoreService.save(keyStore); + return MidmResponse.getSucceedResponse((Object)keyStore); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.keyStoreService.findKeys(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + List allKey = this.keyStoreService.findAll(); + return MidmResponse.getSucceedResponse(allKey); + } + } + + @RequestMapping( + value = {"/delete/{id}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteOta(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String id) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.keyStoreService.delete(id); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, KeyStore keyStore, @RequestParam MultipartFile file) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String originalFileName = file.getOriginalFilename(); + if (!originalFileName.endsWith(".keystore")) { + return null; + } else { + String tempFilePath = this.keyStoreService.getFilePath(keyStore.getId()); + McFile tempFile = new McFile(tempFilePath); + if (!tempFile.getParentFile().exists()) { + tempFile.getParentFile().mkdirs(); + } + + if (tempFile.exists()) { + tempFile.delete(); + } + + try { + if (tempFile.write(file.getInputStream())) { + keyStore.setCertMd5(tempFile); + this.keyStoreService.save(keyStore); + return MidmResponse.getSucceedResponse((Object)tempFile.getName()); + } + } catch (IOException e) { + tempFile.delete(); + String var10001 = e.getMessage(); + return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + } + + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"file/{id}/{fileName}"}, + method = {RequestMethod.GET} + ) + public void getFile(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @PathVariable String id, @PathVariable String fileName) { + User user = UserPrincipal.getUser(authentication); + if (user != null) { + String filePath = this.keyStoreService.getFilePath(id); + McResource.copyFileToResponse(this.servletContext, response, new McFile(filePath), fileName, 0, -1); + } + } +} diff --git a/src/main/java/com/midm/webservice/store/StoreAppsApi.java b/src/main/java/com/midm/webservice/store/StoreAppsApi.java new file mode 100644 index 0000000..3f59ce5 --- /dev/null +++ b/src/main/java/com/midm/webservice/store/StoreAppsApi.java @@ -0,0 +1,293 @@ +package com.midm.webservice.store; + +import com.google.gson.JsonObject; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.store.AppReleaseNote; +import com.midm.model.store.StoreApp; +import com.midm.model.store.StoreAppFile; +import com.midm.service.org.UserService; +import com.midm.service.store.StoreAppService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.security.Principal; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"api/store/apps"}) +public class StoreAppsApi { + @Autowired + private UserService userService; + @Autowired + private StoreAppService storeAppService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveApp(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String oldPackageName) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + StoreApp app = (StoreApp)McJsonUtils.toObject(request, StoreApp.class); + app = this.storeAppService.save(app, oldPackageName); + return MidmResponse.getSucceedResponse((Object)app); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.storeAppService.findApps(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/packages"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getPackages(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam int minSdkVersion, @RequestParam(required = false) String[] packages) { + return MidmResponse.getSucceedResponse(this.storeAppService.findAll(minSdkVersion)); + } + + @RequestMapping( + value = {"/about/{packageName}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAppDetails(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String packageName) { + StoreApp app = this.storeAppService.find(packageName); + return app != null ? MidmResponse.getSucceedResponse((Object)app) : MidmResponse.getResponse(421, "Package not found."); + } + + @RequestMapping( + value = {"/files/{packageName}/{versionCode}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAppFiles(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String packageName, @PathVariable int versionCode) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + List appFiles = this.storeAppService.findAppFiles(packageName, versionCode); + return MidmResponse.getSucceedResponse(appFiles); + } + } + + @RequestMapping( + value = {"/latest/{packageName}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getLatestAppDetails(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String packageName, @RequestParam(name = "checksum",required = false) String certMd5, @RequestParam(required = false,defaultValue = "-1") int versionCode, @RequestParam(required = false,defaultValue = "-1") int sdkVersion) { + StoreAppFile file = this.storeAppService.findLatestAppFile(packageName, versionCode, sdkVersion, certMd5); + return file != null ? MidmResponse.getSucceedResponse((Object)file) : MidmResponse.getResponse(421, "No update needed."); + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteApp(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeAppService.deleteAppFile(fileUuid); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/delete/{packageName}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteAllApp(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String packageName, @RequestParam(required = false,defaultValue = "-1") int versionCode, @RequestParam(required = false,defaultValue = "false") boolean filesOnly) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeAppService.delete(packageName, versionCode, filesOnly); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/releaseNote/add"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveReleaseNote(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, String packageName, int versionCode, @RequestParam(required = false) String[] notes, @RequestParam(required = false) String[] noteNewFunctions, @RequestParam(required = false) Date releasedAt, @RequestParam(required = false) String versionName, @RequestParam(required = false,defaultValue = "-1") int minSdkVersion) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + AppReleaseNote releaseNote = this.storeAppService.updateNote(packageName, versionCode, versionName, minSdkVersion, notes, noteNewFunctions, releasedAt); + return MidmResponse.getSucceedResponse((Object)releaseNote); + } + } + + @RequestMapping( + value = {"/releaseNote/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findReleaseNotes(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, String packageName, @RequestParam(defaultValue = "-1") int page, @RequestParam(defaultValue = "-1") int size, @RequestParam(defaultValue = "-1") int sdkVersion, @RequestParam(required = false) String certMd5, @RequestParam(defaultValue = "true") boolean includeFiles) { + Page releaseNote = this.storeAppService.findReleaseNotes(packageName, sdkVersion, certMd5, page, size); + return MidmResponse.getSucceedResponse(releaseNote); + } + + @RequestMapping( + value = {"/releaseNote/setToFormal"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, String packageName, int versionCode, boolean isFormal) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + AppReleaseNote releaseNote = this.storeAppService.updateNoteIsFormal(packageName, versionCode, isFormal); + return MidmResponse.getSucceedResponse((Object)releaseNote); + } + } + + @RequestMapping( + value = {"/getSdk"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getSDKVersions(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, String packageName) { + List sdkVersions = this.storeAppService.getSdkVersions(packageName); + return MidmResponse.getSucceedResponse(sdkVersions); + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "file") MultipartFile multiPartFile, @RequestParam long lastModified, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String originalFileName = multiPartFile.getOriginalFilename(); + UUID fileUuid = UUID.randomUUID(); + String tempFilePath = this.storeAppService.getTempFilePath("app", fileUuid); + McFile tempFile = new McFile(tempFilePath); + if (!tempFile.getParentFile().exists()) { + tempFile.getParentFile().mkdirs(); + } + + try { + if (tempFile.write(multiPartFile.getInputStream())) { + StoreAppFile tempAppFile = new StoreAppFile(user, fileUuid, tempFile, true); + McFile tempIconFile = new McFile(tempFilePath + ".png"); + if (tempAppFile.getAppInfo().isEmpty()) { + tempFile.delete(); + tempIconFile.delete(); + return MidmResponse.getResponse(400, "May not apk file."); + } else { + String packageName = tempAppFile.getPackageName(); + String storeIconPath = this.storeAppService.getStoreIconPath(packageName); + if ((new McFile(storeIconPath)).exists()) { + tempIconFile.delete(); + } else { + tempIconFile.moveTo(storeIconPath); + } + + StoreApp storeApp = this.storeAppService.find(packageName); + if (storeApp == null) { + storeApp = new StoreApp(packageName); + storeApp.setTitle(tempAppFile.getLabel()); + } + + storeApp.setLastUpdated(new Date()); + this.storeAppService.save(storeApp, (String)null); + long versionCode = tempAppFile.getVersionCode(); + if (!this.storeAppService.releaseNoteExists(packageName, (int)versionCode)) { + this.storeAppService.addReleaseNote(tempAppFile); + } + + this.storeAppService.sign(user, tempFile, originalFileName); + tempFile.delete(); + return MidmResponse.getSucceedResponse((Object)storeApp); + } + } else { + return MidmResponse.getResponse(400, "Write failed : " + tempFile.getPath()); + } + } catch (IOException e) { + tempFile.delete(); + String var10001 = e.getMessage(); + return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + } + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } +} diff --git a/src/main/java/com/midm/webservice/store/StoreOtasApi.java b/src/main/java/com/midm/webservice/store/StoreOtasApi.java new file mode 100644 index 0000000..38c6e1b --- /dev/null +++ b/src/main/java/com/midm/webservice/store/StoreOtasApi.java @@ -0,0 +1,340 @@ +package com.midm.webservice.store; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.file.OtaFile; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.store.StoreOta; +import com.midm.model.store.StoreOtaFile; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.org.UserService; +import com.midm.service.store.StoreOtaService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.security.Principal; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"api/store/otas"}) +public class StoreOtasApi { + @Autowired + private UserService userService; + @Autowired + private StoreOtaService storeOtaService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveOta(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + StoreOta ota = (StoreOta)McJsonUtils.toObject(request, StoreOta.class); + ota = this.storeOtaService.save(ota); + return MidmResponse.getSucceedResponse((Object)ota); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.storeOtaService.findOtas(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAllOtas(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + List otas = this.storeOtaService.findAll(); + return MidmResponse.getSucceedResponse(otas); + } + } + + @RequestMapping( + value = {"/findOtaFiles"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findOtaFiles(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String productId, @RequestParam(defaultValue = "-1") int page, @RequestParam(defaultValue = "-1") int size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page storeOtaFiles = this.storeOtaService.findOtaFiles(productId, page, size); + return MidmResponse.getSucceedResponse(storeOtaFiles); + } + } + + @RequestMapping( + value = {"/releaseNote/add"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveReleaseNote(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid, String[] notes) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + StoreOtaFile otaFile = this.storeOtaService.updateNote(fileUuid, notes); + return MidmResponse.getSucceedResponse((Object)otaFile); + } + } + + @RequestMapping( + value = {"/details/{productId}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getOtaDetails(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String productId) { + StoreOta ota = this.storeOtaService.find(productId); + return ota == null ? MidmResponse.getResponse(421, "System image not found") : MidmResponse.getSucceedResponse((Object)ota); + } + + @RequestMapping( + value = {"/latest"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getLatestDummy(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,defaultValue = "-1") Long buildDate) { + return MidmResponse.getResponse(421, "No product ID is defined."); + } + + @RequestMapping( + value = {"/latest/{productId}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getLatest(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String productId, @RequestParam(required = false) String skuId, @RequestParam(required = false,defaultValue = "-1") Long buildDate) { + StoreOtaFile otaFile = this.storeOtaService.findLatest(productId, skuId, buildDate); + return otaFile == null ? MidmResponse.getResponse(421, "No System image update available.") : MidmResponse.getSucceedResponse((Object)otaFile); + } + + @RequestMapping( + value = {"/latest/{productId}/{skuId}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getLatestBySkuId(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String productId, @PathVariable String skuId, @RequestParam(required = false,defaultValue = "-1") Long buildDate) { + StoreOtaFile otaFile = this.storeOtaService.findLatest(productId, skuId, buildDate); + return otaFile == null ? MidmResponse.getResponse(421, "No System image update available.") : MidmResponse.getSucceedResponse((Object)otaFile); + } + + @RequestMapping( + value = {"/download/{productId}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getLatestOta(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String productId, @RequestParam String cert) { + StoreOta ota = this.storeOtaService.find(productId); + return MidmResponse.getSucceedResponse((Object)ota); + } + + @RequestMapping( + value = {"/delete/{productId}"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteOta(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String productId) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeOtaService.delete(productId); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteOtaFile(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false) String productId) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeOtaService.deleteSingleFile(fileUuid, productId); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestParam long lastModified, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String originalFileName = file.getOriginalFilename(); + if (!originalFileName.endsWith(".zip")) { + return null; + } else { + StoreOtaFile ota = null; + UUID fileUuid = UUID.randomUUID(); + String tempFilePath = this.storeOtaService.getTempFilePath(fileUuid); + McFile tempFile = new McFile(tempFilePath); + if (!tempFile.getParentFile().exists()) { + tempFile.getParentFile().mkdirs(); + } + + try { + if (tempFile.write(file.getInputStream())) { + ota = new StoreOtaFile(user, fileUuid, tempFile); + String name = ota != null ? ota.getName() : null; + if (ota.isRegionImage()) { + tempFile.delete(); + return MidmResponse.getResponse(441, "No region image supported in Store OTA."); + } + + if (Strings.isNullOrEmpty(ota.getProductId())) { + int endIndex = originalFileName.indexOf(95); + if (endIndex > 0) { + String productId = originalFileName.substring(0, endIndex); + if (!Strings.isNullOrEmpty(productId)) { + ota.setProductId(productId); + } + + int startIndex = endIndex + 1; + endIndex = originalFileName.lastIndexOf(95); + if (startIndex < endIndex) { + String displayId = originalFileName.substring(startIndex, endIndex); + if (!Strings.isNullOrEmpty(displayId)) { + ota.setDisplayId(displayId); + } + } + } + } + + if (Strings.isNullOrEmpty(ota.getDisplayId())) { + int startIndex = originalFileName.indexOf(95) + 1; + int endIndex = originalFileName.lastIndexOf(95); + if (startIndex < endIndex) { + String displayId = originalFileName.substring(startIndex, endIndex); + if (!Strings.isNullOrEmpty(displayId)) { + ota.setDisplayId(displayId); + } + } + } + + if (Strings.isNullOrEmpty(ota.getSkuId())) { + String skuId = OtaFile.parseSkuId(originalFileName); + if (!Strings.isNullOrEmpty(skuId)) { + ota.setSkuId(skuId); + } + } + + if (!Strings.isNullOrEmpty(ota.getSkuId()) && !Strings.isNullOrEmpty(ota.getProductId())) { + StoreOta storeOta = this.storeOtaService.find(ota.getProductId()); + if (storeOta == null) { + storeOta = new StoreOta(ota.getProductId()); + storeOta.setDeviceId(ota.getDeviceId()); + } else { + storeOta.setLastUpdated(new Date()); + } + + this.storeOtaService.save(storeOta); + StoreOtaFile existingOtaFile = this.storeOtaService.find(ota.getProductId(), ota.getBuildDate()); + if (existingOtaFile == null) { + ota.setFileName(originalFileName); + ota.setName(Strings.isNullOrEmpty(name) ? ota.getDeviceId() : name); + ota.setLastModified(lastModified); + ota.setLastUpdated(new Date()); + this.storeOtaService.save(ota); + } else { + fileUuid = existingOtaFile.getFileUuid(); + } + + if (this.cloudStorageService.hasCloudStorage()) { + this.cloudStorageService.upload(tempFile, originalFileName, tempFile.getContentType(), "store", "ota", ota.getProductId(), fileUuid); + } + + String storeOtaFilePath = this.storeOtaService.getStoreOtaFilePath(ota.getProductId(), fileUuid); + tempFile.moveTo(storeOtaFilePath); + return MidmResponse.getSucceedResponse((Object)tempFile); + } + + tempFile.delete(); + return MidmResponse.getResponse(441, "Invalid system image."); + } + } catch (IOException e) { + tempFile.delete(); + String var10001 = e.getMessage(); + return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + } + + return MidmResponse.getFailedResponse(); + } + } + } +} diff --git a/src/main/java/com/midm/webservice/store/StoreOtherApi.java b/src/main/java/com/midm/webservice/store/StoreOtherApi.java new file mode 100644 index 0000000..c05c059 --- /dev/null +++ b/src/main/java/com/midm/webservice/store/StoreOtherApi.java @@ -0,0 +1,192 @@ +package com.midm.webservice.store; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.store.StoreOtherFile; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.org.UserService; +import com.midm.service.store.StoreOtherService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.security.Principal; +import java.util.Date; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"api/store/others"}) +public class StoreOtherApi { + @Autowired + private UserService userService; + @Autowired + private StoreOtherService storeOtherService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveApp(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + StoreOtherFile file = (StoreOtherFile)McJsonUtils.toObject(request, StoreOtherFile.class); + if (this.storeOtherService.fileNameExists(file.getFileUuid(), file.getName(), user.getSiteUuid())) { + return MidmResponse.getResponse(419, "File already exist"); + } else { + this.storeOtherService.save(file); + return MidmResponse.getSucceedResponse((Object)file); + } + } + } + + @RequestMapping( + value = {"/findBy"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findBy(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) UUID uuid, @RequestParam(required = false) String alias) { + StoreOtherFile otherFile = null; + if (uuid != null) { + otherFile = this.storeOtherService.findByUuid(uuid); + } else if (otherFile == null && !Strings.isNullOrEmpty(alias)) { + otherFile = this.storeOtherService.findByAlias(alias); + } + + return otherFile == null ? MidmResponse.getResponse(421, "No records.") : MidmResponse.getSucceedResponse((Object)otherFile); + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.storeOtherService.find(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteApp(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeOtherService.deleteFile(fileUuid); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid, @RequestParam(required = false) Long lastModified, @RequestParam(required = false,defaultValue = "true") Boolean notifyToUpdate) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + String fileName = file.getOriginalFilename(); + if (lastModified == null) { + lastModified = (new Date()).getTime(); + } + + StoreOtherFile otherFile = null; + if (fileUuid != null) { + otherFile = this.storeOtherService.findByUuid(fileUuid); + } + + if (otherFile == null) { + otherFile = this.storeOtherService.findByName(fileName); + } + + if (otherFile != null) { + fileUuid = otherFile.getFileUuid(); + otherFile.setLastUpdated(new Date()); + } else { + fileUuid = UUID.randomUUID(); + } + + String filePath = this.storeOtherService.getStoreFilePath("other", fileUuid); + McFile targetFile = new McFile(filePath); + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + try { + if (targetFile.write(file.getInputStream())) { + if (otherFile == null) { + otherFile = new StoreOtherFile(user, fileUuid, targetFile); + otherFile.setLastModified(lastModified); + otherFile.setSiteUuid(user.getSiteUuid()); + otherFile.setFileName(fileName); + otherFile.setName(fileName); + String alias = this.storeOtherService.getNewAlias(new McFile(fileName)); + otherFile.setAlias(alias); + otherFile.setType(file.getContentType()); + } else { + otherFile.setLastModified(lastModified); + otherFile.setLength(targetFile.length()); + } + + if (this.cloudStorageService.hasCloudStorage()) { + this.cloudStorageService.upload(targetFile, fileName, targetFile.getContentType(), "store", "other", fileUuid); + } + + this.storeOtherService.save(otherFile); + if (otherFile.getLength() > 0L) { + return MidmResponse.getSucceedResponse((Object)otherFile); + } + + targetFile.delete(); + return MidmResponse.getFailedResponse(); + } + } catch (IOException e) { + return MidmResponse.getResponse(400, e.getMessage()); + } + + return MidmResponse.getFailedResponse(); + } + } +} diff --git a/src/main/java/com/midm/webservice/store/StoreWebAppApi.java b/src/main/java/com/midm/webservice/store/StoreWebAppApi.java new file mode 100644 index 0000000..d3449f8 --- /dev/null +++ b/src/main/java/com/midm/webservice/store/StoreWebAppApi.java @@ -0,0 +1,237 @@ +package com.midm.webservice.store; + +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.store.StoreWebApp; +import com.midm.service.cloudStorage.CloudStorageService; +import com.midm.service.org.UserService; +import com.midm.service.store.StoreWebAppService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.io.IOException; +import java.security.Principal; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"api/store/webapp"}) +public class StoreWebAppApi { + @Autowired + private UserService userService; + @Autowired + private StoreWebAppService storeWebAppService; + @Autowired + private CloudStorageService cloudStorageService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID fileUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + StoreWebApp webApp = (StoreWebApp)McJsonUtils.toObject(request, StoreWebApp.class); + if (fileUuid == null) { + fileUuid = UUID.randomUUID(); + } + + if (webApp == null) { + webApp = new StoreWebApp(); + } + + webApp.setFileUuid(fileUuid); + webApp.setAppInfo("groupId", "com.mitac"); + webApp.setAppInfo("artifactId", "midm"); + webApp.setAppInfo("buildTime", new Date()); + this.storeWebAppService.save(webApp); + return MidmResponse.getSucceedResponse((Object)webApp); + } + } + + @RequestMapping( + value = {"/saveNotes"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveReleaseNote(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid, @RequestParam(required = false) List notes, @RequestParam(required = false) List notesNewFunction) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeWebAppService.updateNote(uuid, notes, notesNewFunction); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/setToFormal"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String setToFormal(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid, @RequestParam(required = false,defaultValue = "true") boolean isFormal) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeWebAppService.setToFormal(uuid, isFormal); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/latest"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findLatest(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,defaultValue = "com.mitac") String groupId, @RequestParam(required = false,defaultValue = "midm") String artifactId, @RequestParam(required = false,defaultValue = "true") boolean isFormal) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + StoreWebApp webapp = this.storeWebAppService.findLatest(groupId, artifactId, isFormal); + return MidmResponse.getSucceedResponse((Object)webapp); + } + } + + @RequestMapping( + value = {"/getArtifacts"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getArtifactId(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + List artiFactIds = this.storeWebAppService.getArtifacts(); + return MidmResponse.getSucceedResponse(artiFactIds); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,defaultValue = "com.mitac") String groupId, @RequestParam(required = false,defaultValue = "midm") String artifactId, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.storeWebAppService.find(groupId, artifactId, page, size); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid, @RequestParam(required = false,defaultValue = "false") boolean fileOnly) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + this.storeWebAppService.delete(uuid, fileOnly); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestParam MultipartFile file, @RequestParam long lastModified, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String originalFileName = file.getOriginalFilename(); + if (!originalFileName.endsWith(".war") && !originalFileName.endsWith(".jar")) { + return MidmResponse.getResponse(400, "May not webapp file(*.war)."); + } else { + StoreWebApp webapp = null; + UUID fileUuid = UUID.randomUUID(); + String tempFilePath = this.storeWebAppService.getStoreTempFilePath(fileUuid); + McFile tempFile = new McFile(tempFilePath); + if (!tempFile.getParentFile().exists()) { + tempFile.getParentFile().mkdirs(); + } + + try { + if (tempFile.write(file.getInputStream())) { + webapp = new StoreWebApp(user, fileUuid, tempFile); + webapp.setFileName(originalFileName); + StoreWebApp existApp = this.storeWebAppService.find(webapp.getGroupId(), webapp.getArtifactId(), webapp.getVersion()); + if (existApp != null) { + fileUuid = existApp.getFileUuid(); + webapp.setFileUuid(fileUuid); + webapp.setReleaseNote(existApp.getReleaseNote()); + webapp.setIsFormal(existApp.isFormal()); + } + + if (this.cloudStorageService.hasCloudStorage()) { + this.cloudStorageService.upload(tempFile, originalFileName, tempFile.getContentType(), "store", "webapp", fileUuid); + } + + String filePath = this.storeWebAppService.getStoreFilePath(fileUuid); + tempFile.moveTo(filePath); + this.storeWebAppService.save(webapp); + return MidmResponse.getSucceedResponse((Object)webapp); + } else { + return MidmResponse.getResponse(400, "Write failed."); + } + } catch (IOException e) { + tempFile.delete(); + String var10001 = e.getMessage(); + return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + } + } + } + } +} diff --git a/src/main/java/com/midm/webservice/system/AltLocaleApi.java b/src/main/java/com/midm/webservice/system/AltLocaleApi.java new file mode 100644 index 0000000..7e4b266 --- /dev/null +++ b/src/main/java/com/midm/webservice/system/AltLocaleApi.java @@ -0,0 +1,69 @@ +package com.midm.webservice.system; + +import com.google.gson.JsonObject; +import com.midm.model.message.MidmResponse; +import com.midm.model.system.AltLocale; +import com.midm.service.system.LocaleService; +import com.mitac.cell.utils.McJsonUtils; +import java.security.Principal; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/altLocale"}) +public class AltLocaleApi { + @Autowired + private LocaleService localeService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Principal principal) { + AltLocale locale = (AltLocale)McJsonUtils.toObject(request, AltLocale.class); + this.localeService.save(locale); + return MidmResponse.getSucceedResponse((Object)locale); + } + + @RequestMapping( + value = {"/all"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAll(HttpServletRequest request, Principal principal) { + return MidmResponse.getSucceedResponse(this.localeService.findAllAltLocales()); + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Principal principal, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + Page pageResult = this.localeService.findAltLocales(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal) { + AltLocale locale = (AltLocale)McJsonUtils.toObject(request, AltLocale.class); + this.localeService.delete(locale); + return MidmResponse.getSucceedResponse((Object)locale); + } +} diff --git a/src/main/java/com/midm/webservice/system/HelpMessageApi.java b/src/main/java/com/midm/webservice/system/HelpMessageApi.java new file mode 100644 index 0000000..3dcae21 --- /dev/null +++ b/src/main/java/com/midm/webservice/system/HelpMessageApi.java @@ -0,0 +1,182 @@ +package com.midm.webservice.system; + +import com.google.common.base.Strings; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.midm.constant.LocaleConst; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.system.HelpMessage; +import com.midm.security.UserPrincipal; +import com.midm.service.org.UserService; +import com.midm.service.system.HelpMessageService; +import com.mitac.cell.utils.McJsonUtils; +import java.security.Principal; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"api/help"}) +public class HelpMessageApi { + @Autowired + private HelpMessageService helpMessageService; + @Autowired + private UserService userService; + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + Page pageResult = this.helpMessageService.findMessages(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + + @RequestMapping( + value = {"/findCategories"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findOptionCategories(HttpServletRequest request, Principal principal) { + List categories = this.helpMessageService.getOptionCategories(); + return MidmResponse.getSucceedResponse(categories); + } + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,defaultValue = "en-US") String locale, @RequestParam(required = false) String code, @RequestParam(required = false) String title, @RequestParam(required = false) String desc) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + if (!Strings.isNullOrEmpty(code)) { + long updatedCount = this.helpMessageService.save(code, locale, title, desc); + return MidmResponse.getSucceedResponse((Object)updatedCount); + } else { + JsonElement jMessage = McJsonUtils.toJsonElement(request); + if (jMessage != null) { + if (jMessage.isJsonObject()) { + HelpMessage message = (HelpMessage)McJsonUtils.toObject(jMessage, HelpMessage.class); + if (message != null) { + this.helpMessageService.save(message); + this.helpMessageService.loadMessages(); + return MidmResponse.getSucceedResponse(); + } + } else if (jMessage.isJsonArray()) { + HelpMessage[] messages = (HelpMessage[])McJsonUtils.toObject(jMessage, HelpMessage[].class); + this.helpMessageService.save(messages); + this.helpMessageService.loadMessages(); + return MidmResponse.getSucceedResponse(); + } + } + + return MidmResponse.getFailedResponse(); + } + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String code) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + long updatedCount = this.helpMessageService.delete(code); + this.helpMessageService.loadMessages(); + return MidmResponse.getSucceedResponse((Object)updatedCount); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/option/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveOption(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String code, @RequestParam(required = false,defaultValue = "general") String category, @RequestParam String key, @RequestParam String desc) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + long updatedCount = this.helpMessageService.saveOption(code, category, key, desc); + return MidmResponse.getSucceedResponse((Object)updatedCount); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/option/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteOption(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String code, @RequestParam(required = false,defaultValue = "general") String category, @RequestParam String key) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + long updatedCount = this.helpMessageService.deleteOption(code, category, key); + return MidmResponse.getSucceedResponse((Object)updatedCount); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/{code}/html"}, + method = {RequestMethod.GET}, + produces = {"text/html"} + ) + @ResponseBody + public String getHelp(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String code) { + User user = UserPrincipal.getUser(authentication); + String locale = user != null ? user.getLocale() : LocaleConst.DEFAULT_LOCALE.toLanguageTag(); + return this.helpMessageService.getHtmlContent(code, locale); + } + + @RequestMapping( + value = {"/{code}/exists"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String exists(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String code) { + return MidmResponse.getSucceedResponse((Object)this.helpMessageService.exists(code)); + } + + @RequestMapping( + value = {"/reload"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String reload(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + this.helpMessageService.loadMessages(); + return MidmResponse.getSucceedResponse(); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } +} diff --git a/src/main/java/com/midm/webservice/system/HostLicenseApi.java b/src/main/java/com/midm/webservice/system/HostLicenseApi.java new file mode 100644 index 0000000..5375dc3 --- /dev/null +++ b/src/main/java/com/midm/webservice/system/HostLicenseApi.java @@ -0,0 +1,397 @@ +package com.midm.webservice.system; + +import com.google.common.base.Strings; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.midm.model.device.Device; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.model.system.HostLicense; +import com.midm.model.system.StandaloneLicense; +import com.midm.security.UserPrincipal; +import com.midm.service.device.DeviceService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.net.McNetUtils; +import com.mitac.cell.system.McSystemInfo; +import com.mitac.cell.utils.McJsonUtils; +import java.io.File; +import java.nio.file.Paths; +import java.security.Principal; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.apache.catalina.util.ServerInfo; +import org.bson.Document; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.info.BuildProperties; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/host"}) +public class HostLicenseApi { + @Autowired + private BuildProperties buildProperties; + @Autowired + private SettingsService settingsService; + @Autowired + private HostLicenseService licenseService; + @Autowired + private DeviceService deviceService; + @Autowired + private UserService userService; + @Autowired + private MongoTemplate mongoTemplate; + + @RequestMapping( + value = {"/buildInfo"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String buildVersion(HttpServletRequest request, Authentication authentication) { + Document buildInfo = (new Document("version", this.buildProperties.getVersion())).append("time", Date.from(this.buildProperties.getTime())); + return MidmResponse.getSucceedResponse((Object)buildInfo); + } + + @RequestMapping( + value = {"/server"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String serverInfo(HttpServletRequest request, Authentication authentication) { + Document serverInfo = (new Document("server", ServerInfo.getServerInfo())).append("number", ServerInfo.getServerNumber()).append("built", ServerInfo.getServerBuilt()).append("JVM Version", System.getProperty("java.runtime.version")).append("JVM Vendor", System.getProperty("java.vm.vendor")); + return MidmResponse.getSucceedResponse((Object)serverInfo); + } + + @RequestMapping( + value = {"/license"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String licenseKey(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestBody StandaloneLicense standaloneLicense) { + User loggedUser = this.userService.authorizedUser(authentication, accessToken); + if (loggedUser == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + User user = UserPrincipal.getUser(authentication); + if (user != null && (user.hasSystemRole("SUPER_USER") || user.hasRole("SUPERVISOR"))) { + if (standaloneLicense.getUuid() == null) { + standaloneLicense.init(user); + } + + if (standaloneLicense.getSite() == null) { + Site site = this.licenseService.getCurrentSite(user.getSiteUuid()); + standaloneLicense.setSite(site); + } + + HostLicense license = null; + String licenseKey = null; + if (standaloneLicense.getStatus().equalsIgnoreCase("confirmed")) { + license = new HostLicense(standaloneLicense.getHostId(), standaloneLicense.getSystemHash()); + licenseKey = license.generateLicense((Integer)null, standaloneLicense.getDeviceLimit(), standaloneLicense.getValidTo(), (Boolean)null, standaloneLicense.isStandalone()); + standaloneLicense.addNote("license key generated"); + } + + if (Strings.isNullOrEmpty(licenseKey)) { + standaloneLicense.addNote(standaloneLicense.getStatus()); + standaloneLicense.setUpdated(new Date()); + this.licenseService.save(standaloneLicense); + this.licenseService.sendMessageToRecipients(standaloneLicense); + return MidmResponse.getSucceedResponse(); + } else { + standaloneLicense.setLicenseKey(licenseKey); + this.licenseService.sendMessage(standaloneLicense); + standaloneLicense.addNote("send Notification"); + this.licenseService.save(standaloneLicense); + return MidmResponse.getSucceedResponse((Object)license); + } + } else { + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/getLatestLicense"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getLatestStandaloneLicense(HttpServletRequest request, Authentication authentication, @RequestParam UUID uuid) { + StandaloneLicense license = this.licenseService.findLatest(uuid); + return license == null ? MidmResponse.getResponse(421, "No license.") : MidmResponse.getSucceedResponse((Object)license); + } + + @RequestMapping( + value = {"/licenses"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String licenseKey(HttpServletRequest request, Authentication authentication) { + List licenses = this.licenseService.findAll(); + if (licenses != null && licenses.size() != 0) { + for(HostLicense license : licenses) { + license.setHostId(this.settingsService.hostId()); + license.dispatch(); + } + + return MidmResponse.getSucceedResponse(licenses); + } else { + return MidmResponse.getResponse(421, "No license."); + } + } + + @RequestMapping( + value = {"/license/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String saveKey(HttpServletRequest request, Authentication authentication, @RequestParam String systemHash, @RequestParam String licenseKey, @RequestParam(required = false) String hostId) { + User user = UserPrincipal.getUser(authentication); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + if (Strings.isNullOrEmpty(hostId)) { + hostId = this.settingsService.hostId(); + } + + HostLicense license = this.licenseService.find(systemHash); + if (license == null) { + license = new HostLicense(hostId, systemHash, licenseKey); + } else { + license.setHostId(this.settingsService.hostId()); + license.setLicenseKey(licenseKey); + } + + license.dispatch(); + long deviceNumber = this.deviceService.count(Device.class); + if (license.isValidKey()) { + int deviceLimit = license.getDeviceLimit(); + if (deviceLimit > 0 && deviceNumber > (long)deviceLimit) { + return MidmResponse.getResponse(421, String.format("The registered devices exceed the device limit(%d/%d).", deviceNumber, deviceLimit)); + } else if (!license.isValid()) { + return MidmResponse.getResponse(420, "The host license is invalid."); + } else { + license = this.licenseService.save(license); + return MidmResponse.getSucceedResponse((Object)license); + } + } else { + return MidmResponse.getResponse(422, "The license is invalid. It may have different system hash or host ID or invalid license key."); + } + } else { + return MidmResponse.getFailedResponse(); + } + } + + @RequestMapping( + value = {"/license/validate"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String validate(HttpServletRequest request, Authentication authentication, @RequestParam String systemHash, @RequestParam String licenseKey, @RequestParam(required = false) String hostId) { + User user = UserPrincipal.getUser(authentication); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + HostLicense license = this.licenseService.validateLicense(hostId, systemHash, licenseKey); + return MidmResponse.getSucceedResponse((Object)license); + } else { + return MidmResponse.getFailedResponse(); + } + } + + @RequestMapping( + value = {"/license/switch"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String switchPrimary(HttpServletRequest request, Authentication authentication, @RequestParam String systemHash) { + User user = UserPrincipal.getUser(authentication); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + HostLicense license = this.licenseService.setAsPrimary(systemHash); + return license != null ? MidmResponse.getSucceedResponse((Object)license) : MidmResponse.getFailedResponse(); + } else { + return MidmResponse.getFailedResponse(); + } + } + + @RequestMapping( + value = {"/license/remove"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String removeLicense(HttpServletRequest request, Authentication authentication, @RequestParam String systemHash) { + User user = UserPrincipal.getUser(authentication); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + HostLicense license = this.licenseService.find(systemHash); + if (license != null && !license.isPrimary()) { + this.licenseService.delete(systemHash); + return MidmResponse.getSucceedResponse(); + } else { + return MidmResponse.getFailedResponse(); + } + } else { + return MidmResponse.getFailedResponse(); + } + } + + @RequestMapping( + value = {"/license/info"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String licenseInfo(HttpServletRequest request, Authentication authentication, @RequestParam String hostId, @RequestParam String systemHash, @RequestParam String key) { + HostLicense hostLicense = new HostLicense(hostId, systemHash, key); + return MidmResponse.getSucceedResponse((Object)hostLicense); + } + + @RequestMapping( + value = {"/info"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String info(HttpServletRequest request, Authentication authentication) { + McSystemInfo info = new McSystemInfo(); + JsonObject jInfo = McJsonUtils.toJsonElement(info).getAsJsonObject(); + byte[] mac = info.getMacAddress(); + if (mac != null && mac.length > 0) { + jInfo.addProperty("macAddr", McNetUtils.toMacAddressString(mac)); + } + + if (info.getMacAddresses() != null && !info.getMacAddresses().isEmpty()) { + JsonArray jMacs = new JsonArray(); + jInfo.add("macAddresses", jMacs); + info.getMacAddresses().forEach((addr) -> jMacs.add(McNetUtils.toMacAddressString(addr))); + } + + return MidmResponse.getSucceedResponse((Object)jInfo); + } + + @RequestMapping( + value = {"/ip"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String ip(HttpServletRequest request, Authentication authentication) { + return MidmResponse.getSucceedResponse((Object)McNetUtils.getIpAddress()); + } + + @RequestMapping( + value = {"/myip"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String myIp(HttpServletRequest request, Authentication authentication) { + return MidmResponse.getSucceedResponse((Object)request.getRemoteAddr()); + } + + @RequestMapping( + value = {"/dbInfo"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String dbInfo(HttpServletRequest request, Authentication authentication) { + Document result = this.mongoTemplate.executeCommand(new Document("buildInfo", "")); + return MidmResponse.getSucceedResponse((Object)result); + } + + @RequestMapping( + value = {"/dbServerStatus"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String dbServerStatus(HttpServletRequest request, Authentication authentication) { + Document result = this.mongoTemplate.executeCommand(new Document("serverStatus", "")); + return MidmResponse.getSucceedResponse((Object)result); + } + + @RequestMapping( + value = {"/dbStats"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String dbStats(HttpServletRequest request, Authentication authentication) { + Document result = this.mongoTemplate.getDb().runCommand(new Document("dbStats", 1)); + return MidmResponse.getSucceedResponse((Object)result); + } + + @RequestMapping( + value = {"/hash"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String hash(HttpServletRequest request, Authentication authentication, @RequestParam(required = false,defaultValue = "false") boolean forPrimary) { + return MidmResponse.getSucceedResponse((Object)HostLicense.generateSystemHash(forPrimary ? this.licenseService.getPrimaryLicense().getSystemHash() : this.licenseService.getSystemHash())); + } + + @RequestMapping( + value = {"/startedFrom"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String curLicenseInfo(HttpServletRequest request, Authentication authentication) { + Long startedFrom = this.settingsService.startedFrom(); + return MidmResponse.getSucceedResponse(startedFrom == null ? "Not defined" : new Date(startedFrom)); + } + + @RequestMapping( + value = {"/userDir"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String userDir(HttpServletRequest request, Authentication authentication) { + JsonObject jObject = new JsonObject(); + jObject.addProperty("user.dir", System.getProperty("user.dir")); + jObject.addProperty("file.path", (new File("")).getAbsolutePath()); + jObject.addProperty("paths", Paths.get("").toAbsolutePath().toString()); + return MidmResponse.getSucceedResponse((Object)jObject); + } + + @RequestMapping( + value = {"/isExceedDeviceLimit"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getDeviceNumerLimit(HttpServletRequest request, Authentication authentication) { + return MidmResponse.getSucceedResponse((Object)this.deviceService.isExceedDeviceLimit()); + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + Page pageResult = this.licenseService.find(filter, page, siteUuid, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } +} diff --git a/src/main/java/com/midm/webservice/system/LicenseApi.java b/src/main/java/com/midm/webservice/system/LicenseApi.java new file mode 100644 index 0000000..bb10d9f --- /dev/null +++ b/src/main/java/com/midm/webservice/system/LicenseApi.java @@ -0,0 +1,496 @@ +package com.midm.webservice.system; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceLicense; +import com.midm.model.log.MidmLog; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.SiteLicense; +import com.midm.model.org.User; +import com.midm.model.system.LicenseModel; +import com.midm.service.device.DeviceService; +import com.midm.service.log.LogService; +import com.midm.service.org.SiteLicenseService; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.LicenseService; +import com.mitac.cell.utils.McJsonUtils; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/license"}) +public class LicenseApi { + @Autowired + private LicenseService licenseService; + @Autowired + private SiteLicenseService siteLicenseService; + @Autowired + private SiteService siteService; + @Autowired + private DeviceService deviceService; + @Autowired + private UserService userService; + @Autowired + private HostLicenseService hostLicenseService; + @Autowired + private LogService logService; + + @RequestMapping( + value = {"/models"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getModels(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + Page pageResult = this.licenseService.findModels(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/allModels"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAllModels(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String plan, @RequestParam(required = false) boolean requested) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "No user logged in."); + } else { + Site site = this.siteService.findByUuid(user.getSiteUuid()); + List licenseModels; + if (site != null && !requested) { + licenseModels = this.siteLicenseService.getLicenseModels(site); + } else { + licenseModels = this.licenseService.getAllModels(); + } + + return MidmResponse.getSucceedResponse(licenseModels); + } + } + + @RequestMapping( + value = {"/model/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateModel(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + LicenseModel model = (LicenseModel)McJsonUtils.toObject(request, LicenseModel.class); + this.licenseService.save(model); + return MidmResponse.getSucceedResponse((Object)model); + } + } + + @RequestMapping( + value = {"/model/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteModel(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID modelUuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else if (this.siteLicenseService.isAnySiteLicenseUsed(modelUuid)) { + return MidmResponse.getResponse(422, "Already been used."); + } else { + this.licenseService.deleteModel(modelUuid); + return MidmResponse.getSucceedResponse(); + } + } + + @RequestMapping( + value = {"/site"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getSiteLicenses(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false,defaultValue = "false") Boolean licensed, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false) String sortBy, @RequestParam(required = false) Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "No user logged in."); + } else { + Site site = siteUuid != null ? this.siteService.findByUuid(siteUuid) : user.getSite(); + if (site == null && !user.isSystemUser()) { + return MidmResponse.getResponse(415, "No site belonged to nor a system user."); + } else { + Page pageResult = this.siteLicenseService.find(site, licensed, filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + } + } + + @RequestMapping( + value = {"/site/models"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getSiteLicenseModels(HttpServletRequest request, Authentication authentication, Principal principal, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID siteUuid) { + if (this.hostLicenseService.isStandalone()) { + return MidmResponse.getSucceedResponse(); + } else { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "No user logged in."); + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getFailedResponse(); + } else { + List licenseModels = this.siteLicenseService.getLicenseModels(site, site.getPlanName()); + return MidmResponse.getSucceedResponse(licenseModels); + } + } + } + } + + @RequestMapping( + value = {"/site/upgrade"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String exchangeSiteLicense(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = true) UUID siteUuid, @RequestParam(required = false) UUID licenseModelUuid, @RequestParam(required = false,defaultValue = "standard") String plan, @RequestParam(required = false,defaultValue = "0") Integer amount, @RequestParam(required = false) String po, @RequestParam(required = false) String desc, @RequestParam(required = false,defaultValue = "false") boolean autoRenew, @RequestParam(required = false,defaultValue = "false") boolean renewToSameModel, @RequestParam(required = false,defaultValue = "false") boolean applyAll, @RequestParam(required = false,defaultValue = "false") boolean exchangeAlive, @RequestParam(required = false,defaultValue = "false") boolean includeDisabled) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(450, "No site available."); + } else if (user.hasSystemRole("SYSTEM_ADMIN") || user.hasRole("SUPERVISOR") && user.isBelongedToSite(site.getReseller().getUuid())) { + this.siteService.updatePlan(siteUuid, plan); + LicenseModel licenseModel = licenseModelUuid == null ? null : (LicenseModel)this.licenseService.findById(LicenseModel.class, licenseModelUuid); + if (licenseModel != null && !licenseModel.isTrial() && amount > 0) { + SiteLicense siteLicense = new SiteLicense(site); + siteLicense.setWriter(user); + siteLicense.setLicenseModel(licenseModel); + siteLicense.setPlan(plan); + siteLicense.setAmount(amount); + siteLicense.setStatus(SiteLicense.STATUS.CONFIRMED); + if (!Strings.isNullOrEmpty(po)) { + siteLicense.setPo(po); + } + + if (!Strings.isNullOrEmpty(desc)) { + siteLicense.setDesc(desc); + } + + this.siteLicenseService.save(siteLicense); + List licenses = null; + if (site.isChild()) { + licenses = this.deviceService.getFreshLicenses(site.getReseller().getUuid(), plan, licenseModel.getUuid(), amount); + Date newExpiry = licenseModel.getFreshExpiry(new Date()); + + for(DeviceLicense license : licenses) { + license.setChildSiteLicense(siteLicense); + license.setChildSite(site); + license.setExpiry(newExpiry); + } + } else { + licenses = new ArrayList(); + + for(int i = 0; i < amount; ++i) { + licenses.add(new DeviceLicense(siteLicense, plan)); + } + } + + if (licenses != null && licenses.size() != 0) { + List devices = this.deviceService.findDevicesOrderByExpiry(siteUuid, includeDisabled, licenses.size()); + this.deviceService.expireAllPreviousLicenses(site.getUuid()); + if (!devices.isEmpty()) { + Date licensed = new Date(); + if (applyAll) { + for(int i = 0; i < devices.size(); ++i) { + Device device = (Device)devices.get(i); + DeviceLicense license = (DeviceLicense)licenses.get(i); + this.setDeviceLicense(device, license, autoRenew, renewToSameModel, licensed); + } + } else if (exchangeAlive) { + int i = 0; + + for(Device device : devices) { + if (!device.isLicenseExpired() && !device.isTrial()) { + DeviceLicense license = (DeviceLicense)licenses.get(i++); + this.setDeviceLicense(device, license, autoRenew, renewToSameModel, licensed); + } + } + } + } + + this.deviceService.saveDeviceLicenses(licenses); + this.updateSitePlan(user, site, plan); + return MidmResponse.getSucceedResponse((Object)siteLicense); + } else { + this.deviceService.expireAllPreviousLicenses(site.getUuid()); + this.updateSitePlan(user, site, plan); + return MidmResponse.getSucceedResponse(); + } + } else { + this.deviceService.expireAllPreviousLicenses(site.getUuid()); + this.updateSitePlan(user, site, plan); + return MidmResponse.getSucceedResponse(); + } + } else { + return MidmResponse.getResponse(433, "No permission."); + } + } + } + + @RequestMapping( + value = {"/site/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String updateSiteLicense(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = true) UUID siteUuid, @RequestParam(required = true) UUID licenseModelUuid, @RequestParam(required = false) UUID siteLicenseUuid, @RequestParam(required = false,defaultValue = "standard") String plan, @RequestParam(required = true,defaultValue = "0") int amount, @RequestParam(required = false) String po, @RequestParam(required = false) String desc, @RequestParam(required = false,defaultValue = "ORDERED") SiteLicense.STATUS status, @RequestParam(required = false,defaultValue = "false") Boolean applyNow, @RequestParam(required = false,defaultValue = "false") Boolean autoRenew, @RequestParam(required = false,defaultValue = "false") Boolean renewToSameModel, @RequestParam(required = false,defaultValue = "false") Boolean includeDisabled) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(450, "Site not found."); + } else { + if (site.isChild()) { + UUID resellerUuid = site.getReseller().getUuid(); + if (!user.hasRole(resellerUuid, "SUPERVISOR") && (!user.hasRole(siteUuid, "SUPERVISOR") || status != SiteLicense.STATUS.ORDERED && status != SiteLicense.STATUS.CANCELED)) { + return MidmResponse.getResponse(433, "No permission."); + } + } else if (!user.hasSystemRole("SYSTEM_ADMIN") && !user.hasSystemRole("SALES") && (!user.hasRole(site.getUuid(), "SUPERVISOR") || status != SiteLicense.STATUS.ORDERED && status != SiteLicense.STATUS.CANCELED)) { + return MidmResponse.getResponse(433, "No permission."); + } + + LicenseModel licenseModel = this.licenseService.findLicenseModelByUuid(licenseModelUuid); + if (licenseModel == null) { + return MidmResponse.getFailedResponse(); + } else { + SiteLicense siteLicense = siteLicenseUuid == null ? null : this.siteLicenseService.getSiteLicense(siteLicenseUuid); + if (siteLicense == null) { + siteLicense = new SiteLicense(site); + } else { + siteLicense.updated(); + } + + siteLicense.setWriter(user); + siteLicense.setPlan(plan); + siteLicense.setLicenseModel(licenseModel); + siteLicense.setAmount(amount); + siteLicense.setStatus(status); + siteLicense.setPo(po); + siteLicense.setDesc(desc); + this.siteLicenseService.save(siteLicense); + if (status == SiteLicense.STATUS.CONFIRMED) { + List licenses = null; + if (site.isChild()) { + licenses = this.deviceService.getFreshLicenses(site.getReseller().getUuid(), site.getPlanName(), licenseModel.getUuid(), amount); + Date newExpiry = licenseModel.getFreshExpiry(new Date()); + + for(DeviceLicense license : licenses) { + license.setChildSiteLicense(siteLicense); + license.setChildSite(site); + license.setExpiry(newExpiry); + } + } else { + licenses = new ArrayList(); + + for(int i = 0; i < amount; ++i) { + licenses.add(new DeviceLicense(siteLicense, plan)); + } + } + + if (applyNow) { + List devices = this.deviceService.findDevicesToApplyLicense(siteUuid, includeDisabled); + Date licensed = new Date(); + int i = 0; + + for(Device device : devices) { + if (device.isTrial() || device.isLicenseExpired()) { + DeviceLicense license = (DeviceLicense)licenses.get(i++); + this.setDeviceLicense(device, license, autoRenew, renewToSameModel, licensed); + if (i == licenses.size()) { + break; + } + } + } + } + + this.deviceService.saveDeviceLicenses(licenses); + if (siteLicense.isForChildSite()) { + this.siteLicenseService.addLog(siteLicense, false, "assign", "License assigned"); + this.siteLicenseService.addLog(siteLicense, true, "add", "License added"); + } else { + this.siteLicenseService.addLog(siteLicense, false, "add", "License added"); + } + + this.siteLicenseService.sendMessage(siteLicense); + } else { + this.siteLicenseService.sendMessageToRecipients(siteLicense); + } + + return MidmResponse.getSucceedResponse((Object)siteLicense); + } + } + } + } + + @RequestMapping( + value = {"/site/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteSiteLicense(HttpServletRequest request, Principal principal, @RequestParam UUID licenseUuid) { + this.siteLicenseService.deleteSiteLicense(licenseUuid); + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/site/activities"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getSiteActivities(HttpServletRequest request, Principal principal, @RequestParam UUID siteUuid, @RequestParam(required = false,defaultValue = "4") int limit, @RequestParam(required = false,defaultValue = "false") boolean forManagement) { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getFailedResponse(); + } else { + List logs = this.logService.findLinceseActivities(site, limit, forManagement); + return MidmResponse.getSucceedResponse(logs); + } + } + + @RequestMapping( + value = {"/site/logs"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getSiteLogs(HttpServletRequest request, Principal principal, @RequestParam UUID siteUuid, @RequestParam(required = false) String category, @RequestParam(required = false) String sortBy, @RequestParam(required = false) String direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size, @RequestParam(required = false,defaultValue = "false") boolean forManagement) { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getResponse(450, "Site not found."); + } else { + Page logs = this.logService.findLinceseLogs(site, category, page, size, sortBy, direction, forManagement); + return MidmResponse.getSucceedResponse(logs); + } + } + + @RequestMapping( + value = {"/site/logs/clear"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String clearSiteLogs(HttpServletRequest request, Principal principal, @RequestParam UUID siteUuid, @RequestParam(required = false) String category, @RequestParam(required = false,defaultValue = "false") boolean forManagement) { + Site site = this.siteService.findByUuid(siteUuid); + if (site == null) { + return MidmResponse.getFailedResponse(); + } else { + long removed = this.logService.clearLinceseLogs(site, category, forManagement); + return MidmResponse.getSucceedResponse((Object)removed); + } + } + + @RequestMapping( + value = {"/syncExpiry"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String syncExpiry(HttpServletRequest request, Principal principal) { + for(Device device : this.deviceService.findAllDevices()) { + if (device.hasLicense()) { + DeviceLicense license = device.getLicense(); + Date expiry = license.getExpiry(); + if (expiry != null && device.getLicenseExpiry() != null && !device.getLicenseExpiry().equals(expiry)) { + device.setLicenseExpiry(expiry); + this.deviceService.save(device); + } + } + } + + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/touchDevice"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String touchLicenseOfDevice(HttpServletRequest request, Principal principal) { + List devices = this.deviceService.findAllDevices(); + int count = 0; + + for(Device device : devices) { + DeviceLicense license = device.getLicense(); + if (license == null) { + this.deviceService.setTrialLicense(device); + device.setLicense(license); + this.deviceService.save(device); + ++count; + } else if (!license.isTrial() && !device.getSerialNo().equals(license.getDeviceSerial())) { + device.setLicense((DeviceLicense)null); + device.setLicensed((Date)null); + device.setLicenseExpiry((Date)null); + this.deviceService.setLicense(device, license.getLicenseModel().getUuid(), true, license.isAutoRenew(), license.isRenewToSameModel()); + ++count; + } + } + + return MidmResponse.getSucceedResponse((Object)count); + } + + private void updateSitePlan(User user, Site site, String targetPlan) { + this.siteLicenseService.updateSiteLicense(site, targetPlan); + this.siteService.sendMessage(site, targetPlan); + this.logService.save(user, site.getUuid(), "siteLicense_upgrade_success", String.format("SiteLicense upgrade success from (%s) to (%s)", site.getPlanName(), targetPlan)); + } + + private void setDeviceLicense(Device device, DeviceLicense license, boolean autoRenew, boolean renewToSameModel, Date licensed) { + license.setDevice(device); + license.setAutoRenew(autoRenew); + license.setRenewToSameModel(renewToSameModel); + device.setLicense(license); + device.setLicensed(licensed); + this.deviceService.save(device); + this.deviceService.addLicenseLog(license, (Device)null, device, "apply", "License applied."); + } +} diff --git a/src/main/java/com/midm/webservice/system/LocaleApi.java b/src/main/java/com/midm/webservice/system/LocaleApi.java new file mode 100644 index 0000000..2789ec8 --- /dev/null +++ b/src/main/java/com/midm/webservice/system/LocaleApi.java @@ -0,0 +1,99 @@ +package com.midm.webservice.system; + +import com.google.gson.JsonObject; +import com.midm.model.message.MidmResponse; +import com.midm.model.system.ResourceLocale; +import com.midm.service.system.LocaleService; +import com.mitac.cell.utils.McJsonUtils; +import java.security.Principal; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/locale"}) +public class LocaleApi { + @Autowired + private LocaleService localeService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Principal principal) { + ResourceLocale locale = (ResourceLocale)McJsonUtils.toObject(request, ResourceLocale.class); + this.localeService.save(locale); + return MidmResponse.getSucceedResponse((Object)locale); + } + + @RequestMapping( + value = {"/availables"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAvailables(HttpServletRequest request, Principal principal) { + Locale[] locales = Locale.getAvailableLocales(); + Map localeMap = new HashMap(); + + for(Locale locale : locales) { + localeMap.put(locale.toLanguageTag(), locale.getDisplayLanguage(Locale.ENGLISH)); + } + + return MidmResponse.getSucceedResponse((Object)localeMap); + } + + @RequestMapping( + value = {"/all"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAll(HttpServletRequest request, Principal principal) { + return MidmResponse.getSucceedResponse(this.localeService.findAllLocales()); + } + + @RequestMapping( + value = {"/enabled"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getAllEnabled(HttpServletRequest request, Principal principal) { + return MidmResponse.getSucceedResponse(this.localeService.findEnabledLocales()); + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Principal principal, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false,defaultValue = "locale") String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + Page pageResult = this.localeService.findLocales(filter, page, size, sortBy, direction); + return MidmResponse.getSucceedResponse(pageResult); + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal) { + ResourceLocale locale = (ResourceLocale)McJsonUtils.toObject(request, ResourceLocale.class); + this.localeService.delete(locale); + return MidmResponse.getSucceedResponse((Object)locale); + } +} diff --git a/src/main/java/com/midm/webservice/system/PolicyAgreementApi.java b/src/main/java/com/midm/webservice/system/PolicyAgreementApi.java new file mode 100644 index 0000000..b77aeac --- /dev/null +++ b/src/main/java/com/midm/webservice/system/PolicyAgreementApi.java @@ -0,0 +1,102 @@ +package com.midm.webservice.system; + +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.system.PolicyAgreement; +import com.midm.service.org.UserService; +import com.midm.service.system.PolicyAgreementService; +import com.mitac.cell.utils.McJsonUtils; +import java.security.Principal; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping({"/api/agreement"}) +public class PolicyAgreementApi { + @Autowired + private UserService userService; + @Autowired + private PolicyAgreementService policyAgreementService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, HttpServletResponse response, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID uuid) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + PolicyAgreement agreement = (PolicyAgreement)McJsonUtils.toObject(request, PolicyAgreement.class); + PolicyAgreement existPolicy = this.policyAgreementService.findExistAgreement(agreement.getCategory(), agreement.getVersion()); + if (existPolicy != null && !agreement.getUuid().equals(existPolicy.getUuid())) { + return MidmResponse.getResponse(417, "Version duplicated"); + } else { + agreement.setContent(agreement.getContent()); + agreement.setWriter(user); + this.policyAgreementService.save(agreement); + return MidmResponse.getSucceedResponse((Object)agreement); + } + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String filter, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = false,defaultValue = "10") Integer size) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else { + Page pageResult = this.policyAgreementService.findAll(filter, page, size); + return MidmResponse.getSucceedResponse(pageResult); + } + } + + @RequestMapping( + value = {"/findLatest"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findNewestEula(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String category) { + PolicyAgreement agreement = this.policyAgreementService.findlatest(category); + return MidmResponse.getSucceedResponse((Object)agreement); + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (!user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + PolicyAgreement agreement = (PolicyAgreement)McJsonUtils.toObject(request, PolicyAgreement.class); + this.policyAgreementService.delete(agreement); + return MidmResponse.getSucceedResponse((Object)agreement); + } + } +} diff --git a/src/main/java/com/midm/webservice/system/ResourceMessageApi.java b/src/main/java/com/midm/webservice/system/ResourceMessageApi.java new file mode 100644 index 0000000..c087077 --- /dev/null +++ b/src/main/java/com/midm/webservice/system/ResourceMessageApi.java @@ -0,0 +1,229 @@ +package com.midm.webservice.system; + +import com.google.common.base.Strings; +import com.google.gson.JsonObject; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.system.ResourceMessage; +import com.midm.service.org.UserService; +import com.midm.service.system.LocaleService; +import com.midm.service.system.RestoreService; +import com.mitac.cell.doc.CsvReader; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import java.io.IOException; +import java.io.InputStream; +import java.security.Principal; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/message"}) +public class ResourceMessageApi { + @Autowired + private LocaleService localeService; + @Autowired + private UserService userService; + @Autowired + private RestoreService restoreService; + + @RequestMapping( + value = {"/insert"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String add(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam String locale, @RequestParam String code, @RequestParam String message, @RequestParam(required = false) String comment) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + ResourceMessage resourceMessage = this.localeService.getMessage(code); + if (resourceMessage == null) { + resourceMessage = new ResourceMessage(code, locale, message, comment); + } else { + resourceMessage.setMessage(locale, message); + if (McStringUtils.isValid(comment)) { + resourceMessage.setComment(comment); + } + } + + this.localeService.save(resourceMessage); + return MidmResponse.getSucceedResponse((Object)resourceMessage); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + ResourceMessage resourceMessage = (ResourceMessage)McJsonUtils.toObject(request, ResourceMessage.class); + this.localeService.save(resourceMessage); + return MidmResponse.getSucceedResponse((Object)resourceMessage); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/sync"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String sync(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) String syncServer) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + this.restoreService.restore(syncServer); + return MidmResponse.getSucceedResponse(); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/findAll"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String findAll(HttpServletRequest request, Principal principal) { + List messages = this.localeService.findAllMessages(); + return MidmResponse.getSucceedResponse(messages); + } + + @RequestMapping( + value = {"/reload"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String reload(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + this.localeService.loadLocaleAndResources(); + return MidmResponse.getSucceedResponse(); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/find"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Principal principal, @RequestParam(required = false) JsonObject filter, @RequestParam(required = false,defaultValue = "code") String sortBy, @RequestParam(required = false,defaultValue = "ASC") Sort.Direction direction, @RequestParam(required = false,defaultValue = "0") Integer page, @RequestParam(required = true) Integer size) { + Page pageResult = this.localeService.findByPage(ResourceMessage.class, filter, sortBy, direction, page, size); + return MidmResponse.getSucceedResponse(pageResult); + } + + @RequestMapping( + value = {"/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String delete(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + ResourceMessage resourceMessage = (ResourceMessage)McJsonUtils.toObject(request, ResourceMessage.class); + this.localeService.delete(resourceMessage); + return MidmResponse.getSucceedResponse((Object)resourceMessage); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + @RequestMapping( + value = {"/{code}/{locale}"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String getMessage(HttpServletRequest request, Principal principal, @PathVariable String locale, @PathVariable String code) { + String message = this.localeService.getMessage(locale, code); + return MidmResponse.getSucceedResponse((Object)message); + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String upload(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam MultipartFile file) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user != null && user.hasSystemRole("SYSTEM_ADMIN")) { + try { + String contentType = file.getContentType(); + String fileName = file.getOriginalFilename(); + if (!fileName.toLowerCase().endsWith(".zip") && !contentType.endsWith("zip")) { + if (fileName.toLowerCase().endsWith(".csv") || contentType.endsWith("csv")) { + this.restoreCsv(file.getInputStream()); + } + } else { + this.restoreService.restore(file.getInputStream()); + } + } catch (IOException var8) { + return MidmResponse.getFailedResponse(); + } + + return MidmResponse.getSucceedResponse(); + } else { + return MidmResponse.getResponse(415, "Not authorized."); + } + } + + private void restoreCsv(InputStream input) { + CsvReader reader = new CsvReader(input) { + String[] locales = null; + + public void onNewRow(int rowNum, String[] row) { + if (rowNum == 0) { + this.locales = row; + } else { + String code = row[0]; + if (Strings.isNullOrEmpty(code)) { + return; + } + + ResourceMessage message = ResourceMessageApi.this.localeService.findById(code); + if (message == null) { + message = new ResourceMessage(code); + } + + for(int i = 1; i < this.locales.length; ++i) { + String locale = this.locales[i]; + String localizedMessage = row[i]; + if (!Strings.isNullOrEmpty(locale) && !Strings.isNullOrEmpty(localizedMessage)) { + message.setMessage(locale, localizedMessage); + } + } + + ResourceMessageApi.this.localeService.save(message); + } + + } + }; + reader.parseAll(); + } +} diff --git a/src/main/java/com/midm/webservice/system/SystemSettingsApi.java b/src/main/java/com/midm/webservice/system/SystemSettingsApi.java new file mode 100644 index 0000000..297880d --- /dev/null +++ b/src/main/java/com/midm/webservice/system/SystemSettingsApi.java @@ -0,0 +1,133 @@ +package com.midm.webservice.system; + +import com.google.gson.JsonElement; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.User; +import com.midm.model.system.SystemSetting; +import com.midm.security.UserPrincipal; +import com.midm.service.EmailService; +import com.midm.service.file.FileService; +import com.midm.service.org.UserService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.io.McFile; +import com.mitac.cell.utils.McJsonUtils; +import java.awt.image.BufferedImage; +import java.security.Principal; +import javax.imageio.ImageIO; +import javax.servlet.http.HttpServletRequest; +import org.apache.commons.io.FilenameUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping({"/api/settings"}) +public class SystemSettingsApi { + @Autowired + private SettingsService settingsService; + @Autowired + private EmailService emailService; + @Autowired + private UserService userService; + @Autowired + private FileService fileService; + + @RequestMapping( + value = {"/save"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String save(HttpServletRequest request, Principal principal, @RequestBody SystemSetting[] settings) { + return this.settingsService.save(settings) ? MidmResponse.getSucceedResponse((Object)settings) : MidmResponse.getResponse(400, "Device Number has exceeded limitation"); + } + + @RequestMapping( + value = {"/get"}, + method = {RequestMethod.GET}, + produces = {"application/json"} + ) + @ResponseBody + public String find(HttpServletRequest request, Principal principal, String[] keys) { + Iterable settings = this.settingsService.get(keys); + return MidmResponse.getSucceedResponse((Object)settings); + } + + @RequestMapping( + value = {"/mail/test"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String testMail(HttpServletRequest request, Principal principal) { + JsonElement jElement = McJsonUtils.toJsonElement(request); + if (jElement != null && jElement.isJsonObject()) { + String email = jElement.getAsJsonObject().get("email").getAsString(); + this.emailService.sendTestMail(email); + } + + return MidmResponse.getSucceedResponse(); + } + + @RequestMapping( + value = {"/upload"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String uploadBackground(HttpServletRequest request, @RequestParam("file") MultipartFile file, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken) { + User user = this.userService.authorizedUser(authentication, accessToken); + if (user == null) { + return MidmResponse.getResponse(415, "Not authorized."); + } else if (user != null && !user.hasSystemRole("SYSTEM_ADMIN")) { + return MidmResponse.getResponse(433, "No permission."); + } else { + String extension = FilenameUtils.getExtension(file.getOriginalFilename()); + String profilePath = this.fileService.getBackgroundPath(); + McFile targetFile = new McFile(profilePath); + if (targetFile.exists()) { + targetFile.delete(); + } + + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + + try { + BufferedImage image = this.fileService.getBgImage(file); + ImageIO.write(image, extension, targetFile); + return MidmResponse.getSucceedResponse(); + } catch (Exception var10) { + if (targetFile.exists()) { + targetFile.delete(); + } + + return MidmResponse.getFailedResponse(); + } + } + } + + @RequestMapping( + value = {"/background/delete"}, + method = {RequestMethod.POST}, + produces = {"application/json"} + ) + @ResponseBody + public String deleteLogo(HttpServletRequest request, Authentication authentication) { + User user = UserPrincipal.getUser(authentication); + if (user == null) { + return MidmResponse.getFailedResponse(); + } else { + String profilePath = this.fileService.getBackgroundPath(); + (new McFile(profilePath)).delete(); + return MidmResponse.getSucceedResponse(); + } + } +} diff --git a/src/main/java/com/midm/websocket/message/QueryHandler.java b/src/main/java/com/midm/websocket/message/QueryHandler.java new file mode 100644 index 0000000..64c3e57 --- /dev/null +++ b/src/main/java/com/midm/websocket/message/QueryHandler.java @@ -0,0 +1,592 @@ +package com.midm.websocket.message; + +import com.google.api.client.util.Strings; +import com.google.gson.internal.LinkedTreeMap; +import com.midm.model.device.Device; +import com.midm.model.device.DeviceGroup; +import com.midm.model.device.DeviceLicense; +import com.midm.model.file.AppFile; +import com.midm.model.file.OtaFile; +import com.midm.model.message.MIDM_REQUEST; +import com.midm.model.message.MidmPacket; +import com.midm.model.message.MidmQuery; +import com.midm.model.message.MidmResponse; +import com.midm.model.org.Site; +import com.midm.model.org.User; +import com.midm.service.device.DeviceReportService; +import com.midm.service.device.DeviceService; +import com.midm.service.file.DeviceFilesService; +import com.midm.service.file.FileService; +import com.midm.service.log.LogService; +import com.midm.service.message.MidmWebSocketSession; +import com.midm.service.message.WebSocketSessionManager; +import com.midm.service.org.SiteService; +import com.midm.service.org.UserService; +import com.midm.service.system.HostLicenseService; +import com.midm.service.system.SettingsService; +import com.mitac.cell.data.McDecompress; +import com.mitac.cell.db.DbObject; +import com.mitac.cell.utils.McDateTimeUtils; +import com.mitac.cell.utils.McJsonUtils; +import java.nio.ByteBuffer; +import java.util.Date; +import java.util.UUID; +import org.joda.time.DateTime; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; +import org.springframework.web.socket.BinaryMessage; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.PongMessage; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketHandler; +import org.springframework.web.socket.WebSocketMessage; +import org.springframework.web.socket.WebSocketSession; + +/** + * ====================================================================================== + * WebSocket 核心消息分发网关与连接生命周期处理器 (QueryHandler) + * ====================================================================================== + * + *

【架构地位与核心职责】 + * 1. 作为云端与边缘受控移动终端(Android Agent / DPC)及 Web 前端管理端的核心通信网关。 + * 2. 连接生命周期管理: + * - 建立连接认证与识别(区分是设备端 Device 还是管理用户 User); + * - 动态配置单连接缓冲区阈值(避免高频遥测或截屏传输导致 OOM); + * - 断开连接时清理 Session 路由表,触发设备离线状态变更。 + * 3. 混合消息协议解析: + * - 文本消息(TextMessage):处理轻量级心跳与控制命令 JSON; + * - 二进制压缩消息(BinaryMessage):通过 {@link McDecompress} 解压 GZIP 报文,降低蜂窝网络流量开销; + * - 心跳帧(PongMessage):维护自适应心跳时间戳,防连接假死。 + * 4. 业务事件总线(onFeedback): + * - ENROLL(设备注册与许可绑定):校验 SN 序列号、租户白名单、自动签发 License、归属分组; + * - DEVICE_INFO(遥测与固件检测):更新设备运行属性,检测 OTA 固件镜像与 SKU 版本更新; + * - RTC(WebRTC 信令转发):打通 Web 管理员与移动终端的远程桌面/远程控制数据通道; + * - COMMAND / EXEC:下发即时控制指令(锁屏、重启、擦除、应用静默安装); + * - DEVICE_LOG:受控端运行与排障审计日志远程上报。 + * + * @author MiDM Core Platform Team + */ +@Component +public class QueryHandler implements WebSocketHandler { + + @Autowired + private SiteService siteService; + + @Autowired + private DeviceFilesService deviceFilesService; + + /** 会话管理器:维护全局在线 Session 拓扑映射与广播路由 */ + @Autowired + private WebSocketSessionManager sessionManager; + + /** 设备核心服务:处理设备注册、更新、分组与授权逻辑 */ + @Autowired + private DeviceService deviceService; + + /** 设备遥测与监控报表服务(Lazy 延迟加载,防止循环依赖注入) */ + @Autowired + @Lazy + private DeviceReportService deviceReportService; + + @Autowired + private UserService userService; + + @Autowired + private FileService fileService; + + /** 系统授权服务:单租户 / 多租户 License 规则校验 */ + @Autowired + private HostLicenseService hostLicenseService; + + /** 审计日志服务:记录设备注册、策略变更等关键安全事件 */ + @Autowired + private LogService logService; + + @Autowired + private SettingsService settingsService; + + /** + * WebSocket 连接建立成功后的回调(握手完成) + * + * @param session 原生 WebSocket 会话对象 + */ + @Override + public void afterConnectionEstablished(WebSocketSession session) { + try { + // 1. 将原生会话包装为系统定制的 MidmWebSocketSession,提取握手 Header/Query 中的鉴权凭证 + MidmWebSocketSession midmSession = this.sessionManager.toMidmSocketSession(session, true); + if (midmSession != null) { + // 2. 根据系统配置动态设置二进制与文本消息的最大缓冲区容量(防内存溢出) + int bufferSize = this.settingsService.webSocketBufferSize(); + session.setBinaryMessageSizeLimit(bufferSize); + session.setTextMessageSizeLimit(bufferSize); + + // 3. 区分连接主体身份:如果是设备端连接,触发上线事件;如果是后台管理员,注册用户会话 + if (midmSession.getDevice() != null) { + this.sessionManager.onConnected(midmSession); + } else { + User user = midmSession.getUser(); + if (user != null) { + this.sessionManager.register(midmSession); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * WebSocket 连接关闭回调(正常断开或网络异常中止) + * + * @param session 原生 WebSocket 会话对象 + * @param status 断开状态码与原因 + */ + @Override + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { + try { + if (this.sessionManager != null) { + // 从全局路由表中注销该 Session,标记设备为离线状态并广播通知关注该设备的管理前端 + this.sessionManager.onDisconnected(session, status); + } + } catch (Exception var4) { + } + } + + /** + * WebSocket 消息接收总入口 + * + * @param session 原生会话 + * @param message 抽象 WebSocket 消息载荷 + */ + @Override + public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception { + MidmWebSocketSession midmSession = this.sessionManager.toMidmSocketSession(session, false); + if (midmSession != null) { + // 1. 刷新活跃时间戳(Heartbeat Timestamp) + midmSession.updatePongTimeStamp(); + + // 2. 流量统计:如果租户开启了移动蜂窝流量采集,根据阈值触发流量上报 + if (midmSession.getDevice() != null) { + Site site = this.siteService.findByUuid(midmSession.getSiteUuid()); + if (site != null && site.collectDataUsage() && midmSession.needToUpdateDataUsage()) { + this.deviceReportService.updateDataUsage(midmSession.getDevice(), (Date)null); + } + } + + // 3. 根据消息协议帧类型进行分别处理 + if (message instanceof PongMessage) { + if (session.isOpen()) { + midmSession.pong(); + this.handlePongMessage(midmSession, (PongMessage)message); + } else { + midmSession.close(CloseStatus.SESSION_NOT_RELIABLE); + } + } else if (message instanceof TextMessage) { + this.handleTextMessage(midmSession, (TextMessage)message); + } else if (message instanceof BinaryMessage) { + this.handleBinaryMessage(midmSession, (BinaryMessage)message); + } + } + } + + /** + * 处理文本格式消息(JSON 报文或轻量心跳字符串) + * + * @param session 包装会话 + * @param message 文本消息帧 + */ + public void handleTextMessage(MidmWebSocketSession session, TextMessage message) { + String payload = (String)message.getPayload(); + if (!Strings.isNullOrEmpty(payload)) { + if (payload.equals("ping")) { + // 轻量文本心跳处理 + this.sessionManager.onPing(session); + } else { + // 反序列化为统一定义的业务数据包 MidmPacket + MidmPacket packet = (MidmPacket)McJsonUtils.toObject(payload, MidmPacket.class); + if (packet != null) { + this.sessionManager.sendMessage(packet); + } + } + } + } + + /** + * 【IoT 网络优化亮点】处理二进制压缩消息帧 + * + *

移动设备为了节省 4G/5G 流量并提高吞吐量,将大量遥测数据(如设备所有已安装应用、电池历史等) + * 在端侧经过 Deflate/GZIP 压缩后传输。此处进行高性能内存解压后再转为业务包。 + * + * @param session 包装会话 + * @param message 二进制消息帧 + */ + public void handleBinaryMessage(MidmWebSocketSession session, BinaryMessage message) { + ByteBuffer buffer = (ByteBuffer)message.getPayload(); + if (buffer != null) { + // 调用自研压缩工具类进行数据解压 + byte[] decompressed = McDecompress.decompress(buffer.asReadOnlyBuffer()); + if (decompressed != null && decompressed.length != 0) { + MidmPacket packet = (MidmPacket)McJsonUtils.toObject(decompressed, MidmPacket.class); + if (packet != null) { + String request = packet.getQuery().getRequest(); + if (!Strings.isNullOrEmpty(request) && request.equals("ping")) { + this.sessionManager.onPing(session); + } else if (packet.getFeedback() != null) { + // 转发给业务反馈分发总线 + this.onFeedback(session, packet); + } + } + } + } + } + + /** + * 处理客户端响应的 Pong 心跳帧 + */ + protected void handlePongMessage(MidmWebSocketSession session, PongMessage message) { + this.sessionManager.onPong(session); + } + + @Override + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { + } + + /** + * 【核心业务路由器】处理边缘终端返回的各类操作响应(Feedback) + * + * @param midmSession 触发该事件的设备连接会话 + * @param packet 包含 Query 原请求信息与 Feedback 执行结果的数据包 + */ + private void onFeedback(MidmWebSocketSession midmSession, MidmPacket packet) { + MidmQuery query = packet.getQuery(); + MidmResponse feedback = packet.getFeedback(); + String serialNo = midmSession.serialNo(); + + switch (MIDM_REQUEST.get(query.getCode())) { + case ENROLL: + // ------------------------------------------------------------- + // 1. 设备注册与入网接入(Device Enrollment) + // ------------------------------------------------------------- + if (Strings.isNullOrEmpty(serialNo)) { + // 必须包含出厂硬件唯一序列号 SN + midmSession.sendFeedback(461, "No serial no. defined.", (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + } else { + Device device = (Device)McJsonUtils.toObject(McJsonUtils.toJson(feedback.getData()), Device.class); + Device existDevice = this.deviceService.findBySerialNo(midmSession.serialNo()); + UUID siteUuid = existDevice == null ? device.getSiteUuid() : existDevice.getSiteUuid(); + + // 若设备更换了序列号,同步更新索引 + if (existDevice != null && !serialNo.equals(existDevice.getSerialNo())) { + existDevice.setSerialNo(serialNo); + this.deviceService.updateSerialNo(existDevice, serialNo); + existDevice = this.deviceService.findBySerialNo(serialNo); + } + + Site currentSite = this.siteService.findByUuid(siteUuid); + if (currentSite == null) { + midmSession.sendFeedback(451, "No site available.", (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + } else if (currentSite.limitRegisteredDeviceOnly() && existDevice == null) { + // 开启了安全白名单:只允许后台预导入的设备接入 + midmSession.sendFeedback(463, "Enrollement rejected due to un-registered device.", (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + } else { + String siteModel = currentSite.getModel(); + boolean isSelfEnroll = midmSession.selfEnroll(); + + if (existDevice == null) { + // 新设备首次注册 + device.init(); + if (device.getGroupUuid() != null) { + DeviceGroup group = this.deviceService.findDeviceGroup(device.getGroupUuid()); + device.setDeviceGroup(group); + } + + // 自动签发并激活试用/指定 License 许可 + if (!this.hostLicenseService.isStandalone() && (siteModel == null || siteModel.equals("midm"))) { + DeviceLicense license = this.deviceService.setTrialLicense(device); + device.setLicense(license); + String licenseIdName = midmSession.licenseId(); + if (!Strings.isNullOrEmpty(licenseIdName)) { + boolean autoRenew = midmSession.autoRenew(); + boolean renewToSameModel = midmSession.renewToSameModel(); + license = this.deviceService.setLicense(device, licenseIdName, autoRenew, renewToSameModel); + if (license != null) { + device.setLicense(license); + } + } + this.deviceService.activateLicense(license); + } + existDevice = device; + } else { + // 存量设备重新连接/注册 + if (!device.getProfile().isEmpty()) { + existDevice.getProfile().putAll(device.getProfile()); + } + + if (midmSession.ifExistsOption().option != 0) { + // 校验 License 是否过期 + if (!this.hostLicenseService.isStandalone() && existDevice.getLicense().isExpired()) { + midmSession.sendFeedback(115, "Device license expired.", (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + } + + if (isSelfEnroll && !device.isAssociated() && device.getGroupUuid() != null) { + DeviceGroup group = this.deviceService.findDeviceGroup(device.getGroupUuid()); + existDevice.setDeviceGroup(group); + } + + existDevice.setUpdated(); + // 关联设备所属企业员工(User Owner) + Object jOwner = device.getProfile("owner"); + if (jOwner != null) { + LinkedTreeMap map = (LinkedTreeMap)jOwner; + String email = String.valueOf(map.get("email")); + if (!Strings.isNullOrEmpty(email)) { + User user = this.userService.findUserByEmail(siteUuid, email); + if (user != null) { + existDevice.setOwner(user); + } else { + existDevice.setProfile("owner", jOwner); + } + } + } + } + + // 激活或延长 License + if (!this.hostLicenseService.isStandalone() && (siteModel == null || siteModel.equals("midm"))) { + DeviceLicense license = existDevice.getLicense(); + if (license != null) { + if (!license.isActivated() || !existDevice.isEnrolled() && existDevice.getLastCheckedIn() == null) { + license = this.deviceService.activateLicense(license); + } + if (license != null) { + existDevice.setLicense(license); + } + } + } + } + + // 保存并更新设备在 MongoDB 中的最新状态 + boolean wasEnrolled = existDevice.isEnrolled(); + existDevice.setEnabled(true); + existDevice.setEnrolled(new Date()); + existDevice.setLastCheckedIn(); + existDevice.setClientVersion(midmSession.clientVersion()); + this.deviceService.save(existDevice); + + // 记录设备入网审计日志 + this.logService.saveDeviceLog(existDevice.getUuid(), "event", wasEnrolled ? "Re-enrolled" : "Enrolled.", new Date()); + + // 注册全局路由 Session + midmSession.setHolder(existDevice); + this.sessionManager.register(midmSession); + + if (!this.hostLicenseService.isStandalone() && existDevice.getLicense().isExpired()) { + midmSession.sendFeedback(115, "Device license is expired.", (Object)null); + midmSession.close(CloseStatus.NOT_ACCEPTABLE); + } else { + // 注册成功,下发指令与精简设备配置(状态码 111) + midmSession.sendFeedback(111, (String)null, this.sessionManager.optimizeDeviceInfo(existDevice)); + } + } + } + case CHECKIN: + default: + break; + + case DEVICE_INFO: + // ------------------------------------------------------------- + // 2. 设备状态与硬件属性上报(包含 OTA 固件变更检测) + // ------------------------------------------------------------- + DbObject feedBackData = feedback.getDataAsDbObject(); + DbObject newProfile = feedBackData.getDbObject(new String[]{"profile"}); + Device currentDev = midmSession.getDevice(); + if (currentDev.getProfileCategory(new String[]{"software_info"}) != null && newProfile.containsKey("software_info")) { + // 检查设备是否刚完成了系统镜像(System Image)或区域镜像(Region Image)的 OTA 升级 + this.checkImageUpdate(currentDev, newProfile.getDbObject(new String[]{"software_info"})); + } + this.deviceService.updateDeviceInfo(currentDev, newProfile); + break; + + case QUERY: + // ------------------------------------------------------------- + // 3. 通用查询与文件抓取响应(如远程拉取设备日志或截图) + // ------------------------------------------------------------- + if (feedback.getCode() == 138) { + DbObject data = feedback.getDataAsDbObject(); + String hostFile = data.getString("hostFile"); + String fileName = data.getString("fileName"); + Device existDev = this.deviceService.findBySerialNo(serialNo); + User user = this.userService.findUserByUserUuid(packet.getQuery().getSenderUuid()); + Site site = this.siteService.findByUuid(existDev.getSiteUuid()); + String forWhat = query.getCommand(); + this.deviceFilesService.saveFile(UUID.fromString(hostFile), fileName, user, site, existDev, forWhat); + } + + UUID receiverUuid = packet.getRecieverUuid(); + UUID senderUuid = query.getSenderUuid(); + if (senderUuid != null) { + // 将查询响应精准路由回最初发起查询的 Web 用户 Session + this.sessionManager.sendFeedback(midmSession, receiverUuid, senderUuid, packet); + } else { + this.applyFeedback(midmSession, packet); + } + break; + + case COMMAND: + case EXEC: + // ------------------------------------------------------------- + // 4. 控制指令执行结果回传(如锁机、重启、清除数据等) + // ------------------------------------------------------------- + UUID cmdReceiver = packet.getRecieverUuid(); + UUID cmdSender = query.getSenderUuid(); + if (cmdSender != null) { + this.sessionManager.sendFeedback(midmSession, cmdReceiver, cmdSender, packet); + } else { + this.applyFeedback(midmSession, packet); + } + break; + + case RTC: + // ------------------------------------------------------------- + // 5. WebRTC 信令转发(用于远程桌面与远程操作投屏) + // ------------------------------------------------------------- + UUID rtcReceiver = packet.getRecieverUuid(); + UUID rtcSender = query.getSenderUuid(); + if (rtcSender != null) { + this.sessionManager.sendFeedback(midmSession, rtcSender, rtcReceiver, packet); + } + break; + + case DEVICE_STATE: + // ------------------------------------------------------------- + // 6. 设备运行状态推送(广播给关注此租户的管理员界面) + // ------------------------------------------------------------- + UUID stateSender = query.getSenderUuid(); + this.sessionManager.updateDeviceStatus(midmSession.getSiteUuid(), stateSender, packet); + break; + + case DEVICE_LOG: + // ------------------------------------------------------------- + // 7. 设备审计日志入库存储 + // ------------------------------------------------------------- + UUID logDevUuid = query.getSenderUuid(); + String category = query.getParam("category").toString(); + String log = query.getParam("log").toString(); + String date = query.getParam("loggedAt").toString(); + DateTime loggedAt = McDateTimeUtils.parseDate(date, (String)null); + this.logService.saveDeviceLog(logDevUuid, category, log, loggedAt != null ? loggedAt.toDate() : null); + } + } + + /** + * 应用设备的业务反馈(网络状态变化、蜂窝数据消耗等) + */ + private void applyFeedback(MidmWebSocketSession session, MidmPacket packet) { + String request = packet.getQuery().getRequest(); + MidmResponse feedback = packet.getFeedback(); + String command = (String)packet.getParam("command"); + Device device = session.getDevice(); + + switch (request) { + case "network": + if (Strings.isNullOrEmpty(command)) { + this.deviceService.updateProfile(device.getUuid(), "network", feedback.getRefereceAsDbObject()); + } else { + switch (command) { + case "active_network": + // 更新设备当前活跃网络(Wi-Fi / 移动蜂窝网络类型) + DbObject data = feedback.getDataAsDbObject(); + this.deviceService.updateActiveNetwork(device.getUuid(), session.getRemoteIpAddress(), data); + String type = data.getString("type"); + boolean isMobileConnected = "MOBILE".equals(type); + if (isMobileConnected) { + int clientVersion = session.clientVersion(); + // 兼容性保护:若旧版客户端在移动蜂窝网络下存在漫游漏洞,推送最新客户端升级包 + if (this.deviceService.hasRoamingProblem((long)clientVersion)) { + AppFile app = this.fileService.findLatest(device.getUuid(), "com.mitac.midm.client", clientVersion); + if (app != null && app.getVersionCode() > (long)clientVersion) { + session.sendClientUpdateRequest(device, app); + } + } + } + break; + case "data_usage": + // 记录移动数据用量统计 + this.deviceReportService.saveDataUsage(device, feedback.getDataAsDbObject()); + } + } + default: + } + } + + /** + * 【IoT 固件检测算法】对比设备上报的 Build 版本号与镜像信息,判定是否发生了 OTA 固件更新 + * + * @param device 设备持久化实体 + * @param data 设备最新上报的软件与固件构建信息 + */ + private void checkImageUpdate(Device device, DbObject data) { + if (device.getProfileCategory(new String[]{"software_info"}) != null) { + String curDisplayId = data.getString("display_id"); + if (curDisplayId == null) { + curDisplayId = data.getString("build_no"); + } + + String curSkuId = OtaFile.parseSkuId(curDisplayId); + String prevSkuId = device.getSkuId(); + String prevDisplayId = device.getDisplayId(); + if (prevDisplayId == null) { + prevDisplayId = device.getBuildNo(); + } + + boolean isSameSku = true; + // 1. 检查硬件 SKU 是否变更(例如跨产品固件刷机) + if (curSkuId != null && !curSkuId.equals(prevSkuId)) { + isSameSku = false; + this.deviceReportService.resetDevice(device.getUuid()); + this.deviceService.systemImageUpdated(device, isSameSku, prevDisplayId, curDisplayId, -1L, -1L); + } else { + // 2. 检查系统镜像 Build 日期是否有升级 + Long curBuildDate = data.getLong("build_date"); + long prevBuildDate = device.getBuildDate(); + boolean systemImageUpdated = curBuildDate != prevBuildDate; + if (systemImageUpdated) { + boolean isUpgraded = curBuildDate > prevBuildDate; + if (!isUpgraded) { + // 若为固件降级,重置设备状态 + this.deviceReportService.resetDevice(device.getUuid()); + } + this.deviceService.systemImageUpdated(device, isSameSku, prevDisplayId, curDisplayId, prevBuildDate, curBuildDate); + } + + // 3. 检查区域化脚本与定制镜像(Region Image)版本 + String curScriptVersion = data.getString("script_version"); + String preScriptVersion = device.getScriptVersion(); + boolean regionImageUpdated = false; + if (preScriptVersion == null) { + if (curScriptVersion != null) { + regionImageUpdated = true; + } + } else { + regionImageUpdated = curScriptVersion == null || !preScriptVersion.equals(curScriptVersion); + } + + if (regionImageUpdated) { + String prevRegionVersion = device.getRegionImgVersion(); + String curRegionVersion = data.getString("region_version"); + this.deviceService.regionImageUpdated(device, prevRegionVersion, curRegionVersion, preScriptVersion, curScriptVersion); + } + } + } + } + + @Override + public boolean supportsPartialMessages() { + return false; + } +} diff --git a/src/main/java/com/mitac/cell/barcode/QrCode.java b/src/main/java/com/mitac/cell/barcode/QrCode.java new file mode 100644 index 0000000..3df9c7f --- /dev/null +++ b/src/main/java/com/mitac/cell/barcode/QrCode.java @@ -0,0 +1,129 @@ +package com.mitac.cell.barcode; + +import com.google.common.base.Strings; +import com.google.common.io.Files; +import com.google.zxing.BarcodeFormat; +import com.google.zxing.EncodeHintType; +import com.google.zxing.WriterException; +import com.google.zxing.client.j2se.MatrixToImageWriter; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.qrcode.QRCodeWriter; +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.EnumMap; +import java.util.Map; +import javax.imageio.ImageIO; + +public class QrCode { + private static final int DEFAULT_WIDTH = 220; + private static final int DEFAULT_MARGIN = 1; + private String code; + private int width = 220; + private int margin = 1; + + public QrCode() { + } + + public QrCode(String code, int width) { + this.setCode(code); + this.setWidth(width); + } + + public String getCode() { + return this.code; + } + + public void setCode(String code) { + this.code = code; + } + + public int getWdith() { + return this.width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getMargin() { + return this.margin; + } + + public void setMargin(int margin) { + this.margin = margin; + } + + public BufferedImage toImage() { + return toImage(this.code, this.width, this.margin); + } + + public byte[] toBytes(String fileFormat) { + return toBytes(this.toImage(), fileFormat); + } + + public File saveAs(String filePath) { + if (Strings.isNullOrEmpty(filePath)) { + return null; + } else { + String ext = Files.getFileExtension(filePath); + return this.saveAs(filePath, ext); + } + } + + public File saveAs(String filePath, String fileFormat) { + if (Strings.isNullOrEmpty(fileFormat)) { + fileFormat = "png"; + } + + try { + File outputFile = new File(filePath); + ImageIO.write(this.toImage(), fileFormat, outputFile); + return outputFile; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static byte[] toBytes(BufferedImage image, String fileFormat) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + try { + ImageIO.write(image, fileFormat, baos); + return baos.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static BufferedImage toImage(String code, Integer size, Integer margin) { + if (Strings.isNullOrEmpty(code)) { + return null; + } else { + if (size == null || size <= 16) { + size = 220; + } + + if (margin == null || margin < 0) { + margin = 1; + } + + Map hints = new EnumMap(EncodeHintType.class); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + hints.put(EncodeHintType.MARGIN, margin); + hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); + + try { + BitMatrix bitMatrix = (new QRCodeWriter()).encode(code, BarcodeFormat.QR_CODE, size, size, hints); + return MatrixToImageWriter.toBufferedImage(bitMatrix); + } catch (WriterException e) { + e.printStackTrace(); + return null; + } + } + } +} diff --git a/src/main/java/com/mitac/cell/constant/DateTimeConst.java b/src/main/java/com/mitac/cell/constant/DateTimeConst.java new file mode 100644 index 0000000..98675aa --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/DateTimeConst.java @@ -0,0 +1,13 @@ +package com.mitac.cell.constant; + +public class DateTimeConst { + public static final String FORMAT_DATE_4_DIGIT_PASSWORD = "MMdd"; + public static final String FORMAT_DATE_6_DIGIT_PASSWORD = "yyMMdd"; + public static final String FORMAT_DATE_8_DIGIT_PASSWORD = "yyyyMMdd"; + public static final long ONE_MINUTES = 60000L; + public static final long ONE_HOUR = 3600000L; + public static final long HALF_HOUR = 1800000L; + public static final long QUATER_HOUR = 900000L; + public static final long ONE_DAY = 86400000L; + public static final long ONE_WEEK = 604800000L; +} diff --git a/src/main/java/com/mitac/cell/constant/GeneralConst.java b/src/main/java/com/mitac/cell/constant/GeneralConst.java new file mode 100644 index 0000000..1539761 --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/GeneralConst.java @@ -0,0 +1,13 @@ +package com.mitac.cell.constant; + +public class GeneralConst { + public static final String KEY_KEY = "key"; + public static final String KEY_AUTH_KEY = "auth_key"; + public static final String KEY_ID = "id"; + public static final String KEY_NAME = "name"; + public static final String KEY_THEME = "theme"; + public static final String VALUE_DEFAULT = "default"; + public static final String CATEGORY_APP = "app"; + public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L; + public static final String KEY_LANGUAGE = "language"; +} diff --git a/src/main/java/com/mitac/cell/constant/LocaleConst.java b/src/main/java/com/mitac/cell/constant/LocaleConst.java new file mode 100644 index 0000000..e21681d --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/LocaleConst.java @@ -0,0 +1,11 @@ +package com.mitac.cell.constant; + +import java.util.Locale; + +public class LocaleConst { + public static final Locale DEFAULT_LOCALE; + + static { + DEFAULT_LOCALE = Locale.US; + } +} diff --git a/src/main/java/com/mitac/cell/constant/LocationConst.java b/src/main/java/com/mitac/cell/constant/LocationConst.java new file mode 100644 index 0000000..9f5ba6e --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/LocationConst.java @@ -0,0 +1,8 @@ +package com.mitac.cell.constant; + +public class LocationConst { + public static String KEY_LAT = "lat"; + public static String KEY_LATITUDE = "latitude"; + public static String KEY_LON = "lon"; + public static String KEY_LONGITUDE = "longitude"; +} diff --git a/src/main/java/com/mitac/cell/constant/MessageConst.java b/src/main/java/com/mitac/cell/constant/MessageConst.java new file mode 100644 index 0000000..08ad6db --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/MessageConst.java @@ -0,0 +1,21 @@ +package com.mitac.cell.constant; + +public class MessageConst { + public static final String ID = "id"; + public static final String FROM = "from"; + public static final String REPLY_TO = "replyto"; + public static final String TO = "to"; + public static final String CC = "cc"; + public static final String BCC = "bcc"; + public static final String TAG = "tag"; + public static final String TYPE = "type"; + public static final String WEB_URL = "web_url"; + public static final String HEADERS = "headers"; + public static final String SUBJECT = "subject"; + public static final String TEXT = "text"; + public static final String HTML = "html"; + public static final String ATTR = "attr"; + public static final String ATTACHMENT = "attachment"; + public static final String ATTACHMENT_URL = "attachment_url"; + public static final String INLINE_IMAGE = "inline_image"; +} diff --git a/src/main/java/com/mitac/cell/constant/PropertyConst.java b/src/main/java/com/mitac/cell/constant/PropertyConst.java new file mode 100644 index 0000000..7d0a003 --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/PropertyConst.java @@ -0,0 +1,63 @@ +package com.mitac.cell.constant; + +public class PropertyConst { + public static final String ROLE = "role"; + public static final String ADMIN = "admin"; + public static final String ADMINISTRATOR = "Administrator"; + public static final String NAME = "name"; + public static final String FILE_NAME = "fileName"; + public static final String CONTENT_TYPE = "contentType"; + public static final String FILE_URL = "fileUrl"; + public static final String ICON_NAME = "iconName"; + public static final String ICON_URL = "iconUrl"; + public static final String ICON_ID = "iconId"; + public static final String DEVELOPER = "developer"; + public static final String DESC = "desc"; + public static final String LENGTH = "length"; + public static final String CHECKSUM = "checksum"; + public static final String LAST_MODIFIED = "lastModified"; + public static final String TYPE = "type"; + public static final String AB_UPDATE = "abUpdate"; + public static final String BUILD_DATE = "buildDate"; + public static final String BUILD_TIME = "buildTime"; + public static final String POST_BUILD_DATE = "postBuildDate"; + public static final String PRODUCT_ID = "productId"; + public static final String TARGET_PRODUCT = "targetProduct"; + public static final String DEVICE_ID = "deviceId"; + public static final String SKU_ID = "skuId"; + public static final String COMPATIBLE_SKU_IDS = "compatibleSkuIds"; + public static final String DISPLAY_ID = "displayId"; + public static final String PRODUCT_DISPLAY_ID = "productDisplayId"; + public static final String PRE_DISPLAY_ID = "preDisplayId"; + public static final String BUILD_TYPE = "buildType"; + public static final String BUILD_TAGS = "buildTags"; + public static final String OTA_CERT = "otaCert"; + public static final String BRAND = "brand"; + public static final String CUSTOMER = "customer"; + public static final String CUSTOMER_ID = "customerId"; + public static final String PART_NO = "partNo"; + public static final String OS_VERSION = "osVersion"; + public static final String SCRIPT_VERSION = "scriptVersion"; + public static final String RELEASE_VERSION = "releaseVersion"; + public static final String MARKET_NAME_1 = "marketName1"; + public static final String MARKET_NAME_2 = "marketName2"; + public static final String SDK = "sdk"; + public static final String SECURITY_PATCH = "securityPatch"; + public static final String MODEM_SKU = "modemSku"; + public static final String MODEM_FIRMWARE_VERSION = "modemFirmwareVersion"; + public static final String MODEM_FIRMWARE_LONG_VERSION = "modemFirmwareLongVersion"; + public static final String PRE_BUILD = "preBuild"; + public static final String POST_BUILD = "postBuild"; + public static final String PACKAGE = "package"; + public static final String PACKAGE_NAME = "packageName"; + public static final String SHARED_UID = "sharedUid"; + public static final String LABEL = "label"; + public static final String VERSION = "version"; + public static final String VERSION_CODE = "versionCode"; + public static final String VERSION_NAME = "versionName"; + public static final String MIN_SDK_VERSION = "minSdkVersion"; + public static final String MAX_SDK_VERSION = "maxSdkVersion"; + public static final String TARGET_SDK_VERSION = "targetSdkVersion"; + public static final String USER_PERMISSION = "userPermission"; + public static final String CERT_MD5 = "certMd5"; +} diff --git a/src/main/java/com/mitac/cell/constant/SizeConst.java b/src/main/java/com/mitac/cell/constant/SizeConst.java new file mode 100644 index 0000000..dfa1291 --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/SizeConst.java @@ -0,0 +1,14 @@ +package com.mitac.cell.constant; + +public class SizeConst { + public static long SIZE_1K = 1024L; + public static long SIZE_1M; + public static long SIZE_1G; + public static long SIZE_1T; + + static { + SIZE_1M = SIZE_1K * SIZE_1K; + SIZE_1G = SIZE_1M * SIZE_1K; + SIZE_1T = SIZE_1G * SIZE_1K; + } +} diff --git a/src/main/java/com/mitac/cell/data/McCompress.java b/src/main/java/com/mitac/cell/data/McCompress.java new file mode 100644 index 0000000..25fc777 --- /dev/null +++ b/src/main/java/com/mitac/cell/data/McCompress.java @@ -0,0 +1,61 @@ +package com.mitac.cell.data; + +import com.google.common.base.Charsets; +import java.io.ByteArrayOutputStream; +import java.util.zip.Deflater; + +public class McCompress extends Deflater { + private static int BUF_SIZE = 1024; + + public McCompress() { + } + + public McCompress(byte[] source) { + this.setInput(source); + } + + public McCompress(byte[] source, int level) { + super(level); + this.setInput(source); + } + + public McCompress(byte[] source, int level, boolean noHeader) { + super(level, noHeader); + this.setInput(source); + } + + public void setSource(byte[] source) { + this.setInput(source); + } + + public byte[] toByteArray() { + this.finish(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[BUF_SIZE]; + + while(!this.finished()) { + int count = this.deflate(buffer); + + try { + baos.write(buffer, 0, count); + } catch (OutOfMemoryError e) { + e.printStackTrace(); + } + } + + this.end(); + return baos.toByteArray(); + } + + public static byte[] compress(byte[] source, int level, boolean noHeader) { + return (new McCompress(source, level, noHeader)).toByteArray(); + } + + public static byte[] compress(byte[] source) { + return compress(source, 9, true); + } + + public static byte[] compress(String source) { + return compress(source.getBytes(Charsets.UTF_8), 9, true); + } +} diff --git a/src/main/java/com/mitac/cell/data/McDecompress.java b/src/main/java/com/mitac/cell/data/McDecompress.java new file mode 100644 index 0000000..709cc62 --- /dev/null +++ b/src/main/java/com/mitac/cell/data/McDecompress.java @@ -0,0 +1,74 @@ +package com.mitac.cell.data; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.util.zip.DataFormatException; +import java.util.zip.Inflater; + +public class McDecompress extends Inflater { + private static int BUF_SIZE = 1024; + + public McDecompress() { + } + + public McDecompress(byte[] source) { + this.setInput(source); + } + + public McDecompress(byte[] source, boolean noHeader) { + super(noHeader); + this.setInput(source); + } + + public McDecompress(ByteBuffer source) { + this.setSource(source); + } + + public McDecompress(ByteBuffer source, boolean noHeader) { + super(noHeader); + this.setSource(source); + } + + public void setSource(ByteBuffer source) { + byte[] bytes = new byte[source.remaining()]; + source.get(bytes, 0, bytes.length); + this.setInput(bytes); + } + + public void setSource(byte[] source) { + this.setInput(source); + } + + public byte[] toByteArray() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[BUF_SIZE]; + + try { + while(!this.needsInput()) { + int count = this.inflate(buffer); + baos.write(buffer, 0, count); + } + } catch (DataFormatException e) { + e.printStackTrace(); + } + + this.end(); + return baos.toByteArray(); + } + + public static byte[] decompress(byte[] source, boolean noHeader) { + return (new McDecompress(source, noHeader)).toByteArray(); + } + + public static byte[] decompress(byte[] source) { + return decompress(source, true); + } + + public static byte[] decompress(ByteBuffer source, boolean noHeader) { + return (new McDecompress(source, noHeader)).toByteArray(); + } + + public static byte[] decompress(ByteBuffer source) { + return decompress(source, true); + } +} diff --git a/src/main/java/com/mitac/cell/data/McXml.java b/src/main/java/com/mitac/cell/data/McXml.java new file mode 100644 index 0000000..c0ff5a5 --- /dev/null +++ b/src/main/java/com/mitac/cell/data/McXml.java @@ -0,0 +1,87 @@ +package com.mitac.cell.data; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +public class McXml { + private static final String TAG_SOURCE = "src"; + private File parentDir; + + public JsonObject load(File file) throws ParserConfigurationException, SAXException, IOException { + if (file.exists()) { + this.parentDir = file.getParentFile(); + InputStream is = new FileInputStream(file); + return this.load(is); + } else { + return null; + } + } + + public JsonObject load(InputStream is) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); + Document doc = documentBuilder.parse(is); + Element root = doc.getDocumentElement(); + return this.toJsonObject(root); + } + + private JsonObject toJsonObject(Element root) throws ParserConfigurationException, SAXException, IOException { + JsonObject jParent = new JsonObject(); + NamedNodeMap attributes = root.getAttributes(); + if (attributes != null && attributes.getLength() > 0) { + for(int i = 0; i < attributes.getLength(); ++i) { + String name = attributes.item(i).getNodeName(); + String value = attributes.item(i).getNodeValue(); + if (name.equals("src")) { + JsonObject jChild = this.load(new File(this.parentDir, value)); + + for(Map.Entry entry : jChild.entrySet()) { + jParent.add((String)entry.getKey(), (JsonElement)entry.getValue()); + } + } else { + jParent.addProperty(name, value); + } + } + } + + NodeList nodeList = root.getChildNodes(); + + for(int i = 0; i < nodeList.getLength(); ++i) { + Node node = nodeList.item(i); + if (node.getNodeType() == 1) { + String name = node.getNodeName(); + JsonObject jChildProperties = this.toJsonObject((Element)node); + JsonElement jChild = jParent.get(name); + if (jChild != null && !jChild.isJsonNull()) { + if (jChild.isJsonArray()) { + jChild.getAsJsonArray().add(jChildProperties); + } else if (jChild.isJsonObject()) { + JsonArray jArray = new JsonArray(); + jArray.add(jChild); + jArray.add(jChildProperties); + jParent.add(name, jArray); + } + } else { + jParent.add(name, jChildProperties); + } + } + } + + return jParent; + } +} diff --git a/src/main/java/com/mitac/cell/db/DbObject.java b/src/main/java/com/mitac/cell/db/DbObject.java new file mode 100644 index 0000000..3902cd9 --- /dev/null +++ b/src/main/java/com/mitac/cell/db/DbObject.java @@ -0,0 +1,215 @@ +package com.mitac.cell.db; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.bson.Document; + +public class DbObject extends Document { + private static final long serialVersionUID = 1L; + + public DbObject() { + } + + public DbObject(String key, Object value) { + super(key, value); + } + + public DbObject(Map map) { + super(map); + } + + public String getString(String key, String defaultValue) { + Object value = this.get(key); + + try { + return value != null ? String.valueOf(value) : defaultValue; + } catch (Exception var5) { + return defaultValue; + } + } + + public Boolean getBoolean(Object key) { + return this.getBoolean(key, false); + } + + public boolean getBoolean(Object key, boolean defaultValue) { + try { + return super.getBoolean(key, defaultValue); + } catch (Exception var4) { + return this.containsKey(key) && this.get(key).equals("true"); + } + } + + public Integer getInteger(Object key) { + return this.getInteger(key, -1); + } + + public int getInteger(Object key, int defaultValue) { + Number value = this.getNumber(key); + return value != null ? value.intValue() : defaultValue; + } + + public Long getLong(Object key) { + return this.getLong(key, -1L); + } + + public long getLong(Object key, long defaultValue) { + Number value = this.getNumber(key); + return value != null ? value.longValue() : defaultValue; + } + + public Float getFloat(Object key) { + return this.getFloat(key, -1.0F); + } + + public float getFloat(Object key, float defaultValue) { + Number value = this.getNumber(key); + return value != null ? value.floatValue() : defaultValue; + } + + public Double getDouble(Object key) { + return this.getDouble(key, (double)-1.0F); + } + + public double getDouble(Object key, double defaultValue) { + Number value = this.getNumber(key); + return value != null ? value.doubleValue() : defaultValue; + } + + private Number getNumber(Object key) { + try { + Object value = this.get(key); + if (value instanceof String) { + return Double.parseDouble((String)value); + } else { + return value instanceof Number ? (Number)value : null; + } + } catch (Exception var3) { + return null; + } + } + + public UUID getUuid(String key) { + Object value = this.get(key); + if (value == null) { + return null; + } else if (value instanceof UUID) { + return (UUID)value; + } else if (value instanceof String) { + try { + return UUID.fromString((String)value); + } catch (Exception var4) { + return null; + } + } else if (value instanceof byte[]) { + try { + byte[] bytes = (byte[])value; + return bytes.length == 16 ? UUID.nameUUIDFromBytes((byte[])value) : null; + } catch (Exception var5) { + return null; + } + } else { + return null; + } + } + + public void convertUuid(String key) { + Object value = this.get(key); + if (!(value instanceof UUID)) { + if (value instanceof String) { + try { + this.put(key, this.getUuid(key)); + } catch (Exception var4) { + } + } + + } + } + + public DbObject getDbObject(String... keys) { + DbObject dbObject = this; + + for(String key : keys) { + Object value = dbObject.get(key); + if (value == null) { + Object var8 = new DbObject(); + dbObject.put(key, var8); + dbObject = var8; + } else if (value instanceof DbObject) { + dbObject = (DbObject)value; + } else if (value instanceof Map) { + Object var9 = new DbObject((Map)value); + dbObject.put(key, var9); + dbObject = var9; + } else { + Object var10 = new DbObject(); + dbObject.put(key, var10); + dbObject = var10; + } + } + + return dbObject; + } + + public List getList(Object key, Class clazz) { + if (clazz.equals(DbObject.class)) { + List list = super.getList(key, Object.class); + if (list != null) { + List listDbObject = new ArrayList(); + list.forEach((item) -> { + if (item instanceof Map) { + listDbObject.add(new DbObject((Map)item)); + } + + }); + this.put((String)key, listDbObject); + return listDbObject; + } else { + return null; + } + } else if (clazz.equals(UUID.class)) { + List list = super.getList(key, Object.class); + if (list != null) { + List listDbObject = new ArrayList(); + list.forEach((item) -> { + if (item instanceof UUID) { + listDbObject.add(item); + } else if (item instanceof String) { + listDbObject.add(UUID.fromString((String)item)); + } + + }); + this.put((String)key, listDbObject); + return listDbObject; + } else { + return null; + } + } else { + return super.getList(key, clazz); + } + } + + public DbObject toPlat() { + return toFlat((String)null, this); + } + + public static DbObject toFlat(String parentKey, DbObject nestedObj) { + DbObject flatObj = new DbObject(); + String prefixKey = parentKey != null ? parentKey + "." : ""; + + for(Map.Entry entry : nestedObj.entrySet()) { + Object value = entry.getValue(); + if (value instanceof DbObject) { + flatObj.putAll(toFlat(prefixKey + (String)entry.getKey(), (DbObject)entry.getValue())); + } else if (value instanceof Map) { + flatObj.putAll(toFlat(prefixKey + (String)entry.getKey(), new DbObject((Map)entry.getValue()))); + } else { + flatObj.put(prefixKey + (String)entry.getKey(), value); + } + } + + return flatObj; + } +} diff --git a/src/main/java/com/mitac/cell/db/util/JpaQuery.java b/src/main/java/com/mitac/cell/db/util/JpaQuery.java new file mode 100644 index 0000000..e821082 --- /dev/null +++ b/src/main/java/com/mitac/cell/db/util/JpaQuery.java @@ -0,0 +1,68 @@ +package com.mitac.cell.db.util; + +import com.google.common.base.Joiner; +import com.mitac.cell.utils.McStringUtils; + +public class JpaQuery { + private StringBuilder sbColumns = new StringBuilder(); + private StringBuilder sbConditions = new StringBuilder(); + private String tableName; + private String orderBy; + + public JpaQuery(String tableName) { + this.setTableName(tableName); + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public void setOrderBy(String orderBy) { + this.orderBy = orderBy; + } + + public void addColumn(String column) { + if (this.sbColumns.length() > 0) { + this.sbColumns.append(", "); + } + + this.sbColumns.append(column); + } + + public void addColumn(String... column) { + this.addColumn(Joiner.on(",").join(column)); + } + + public void addJsonColumn(String dbColumn, String columnName) { + String column = "CAST(COLUMN_JSON(" + dbColumn + ") AS CHAR) AS " + columnName; + this.addColumn(column); + } + + public void addJsonColumn(String dbColumn, String dynamicColumn, String type, String columnName) { + String column = "COLUMN_GET(" + dbColumn + ", " + dynamicColumn + " AS " + type + ") AS " + columnName; + this.addColumn(column); + } + + public String toQuery() { + StringBuilder sbQuery = new StringBuilder("SELECT "); + if (this.sbColumns.length() == 0) { + sbQuery.append(" * "); + } else { + sbQuery.append(this.sbColumns); + } + + sbQuery.append(" FROM "); + sbQuery.append(this.tableName); + if (this.sbConditions.length() > 0) { + sbQuery.append(" WHERE "); + sbQuery.append(this.sbConditions); + } + + if (McStringUtils.isValid(this.orderBy)) { + sbQuery.append(" ORDER BY "); + sbQuery.append(this.orderBy); + } + + return sbQuery.toString(); + } +} diff --git a/src/main/java/com/mitac/cell/db/util/McDbUtils.java b/src/main/java/com/mitac/cell/db/util/McDbUtils.java new file mode 100644 index 0000000..8898986 --- /dev/null +++ b/src/main/java/com/mitac/cell/db/util/McDbUtils.java @@ -0,0 +1,13 @@ +package com.mitac.cell.db.util; + +public class McDbUtils { + public static int from(int page, int size) { + return page * size; + } + + public static int to(int page, int size, int total) { + ++page; + int max = page * size; + return total - max > 0 ? max : total; + } +} diff --git a/src/main/java/com/mitac/cell/db/util/McMongoUtils.java b/src/main/java/com/mitac/cell/db/util/McMongoUtils.java new file mode 100644 index 0000000..3d89aac --- /dev/null +++ b/src/main/java/com/mitac/cell/db/util/McMongoUtils.java @@ -0,0 +1,323 @@ +package com.mitac.cell.db.util; + +import com.google.common.base.Strings; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import com.mongodb.client.ListIndexesIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.model.IndexOptions; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; +import java.util.regex.Pattern; +import org.apache.commons.compress.utils.Sets; +import org.bson.Document; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; + +public class McMongoUtils { + public static Pageable toPageable(int page, int size, String sortBy, String direction) { + Sort.Direction dir = toDirection(direction); + return dir != null && !McStringUtils.isNullOrEmpty(sortBy) ? PageRequest.of(page, size, dir, new String[]{sortBy}) : PageRequest.of(page, size); + } + + public static Sort.Direction toDirection(String direction) { + try { + return Direction.valueOf(direction.trim().toUpperCase()); + } catch (Exception var2) { + return null; + } + } + + public static Query toQuery(JsonObject jFilter, String sortBy, Sort.Direction direction) { + Sort sort = Strings.isNullOrEmpty(sortBy) ? null : Sort.by(direction, new String[]{sortBy}); + Query query = new Query(); + if (sort != null) { + query.with(sort); + } + + if (jFilter != null && !jFilter.isJsonNull()) { + addFilter(query, jFilter); + return query; + } else { + return query; + } + } + + public static void addFilter(Query query, JsonObject jFilter) { + for(Map.Entry jElement : jFilter.entrySet()) { + String key = (String)jElement.getKey(); + JsonElement jValue = (JsonElement)jElement.getValue(); + if (jValue.isJsonPrimitive()) { + String value = jValue.getAsString(); + if (McStringUtils.isNullOrEmpty(value)) { + query.addCriteria(toEmptyCriteria(key)); + } else if (key.equals("sites.siteUuid")) { + Criteria criElem = toUuidCriteria("siteUuid", UUID.fromString(value)); + if (jFilter.has("sites.groupUuid")) { + JsonElement jGroups = jFilter.get("sites.groupUuid"); + if (jGroups.isJsonNull()) { + criElem.and("groupUuid").exists(false); + } else if (jGroups.isJsonArray()) { + criElem.andOperator(new Criteria[]{toOrCriteria("groupUuid", jGroups.getAsJsonArray())}); + } + } + + query.addCriteria(Criteria.where("sites").elemMatch(criElem)); + } else if (!key.equals("appInfo.versionCode") && !key.equals("appInfo.minSdkVersion") && !key.equals("appInfo.targetSdkVersion") && !key.equals("appInfo.maxSdkVersion")) { + if (key.equals("otaInfo.skuId")) { + query.addCriteria((new Criteria()).orOperator(new Criteria[]{toLikeCriteria(key, value), toLikeCriteria("otaInfo.customerId", value)})); + } else if (key.contains(".")) { + if (key.toLowerCase().endsWith("uuid")) { + try { + UUID uuid = UUID.fromString(value); + query.addCriteria(toUuidCriteria(key, uuid)); + } catch (Exception var10) { + query.addCriteria(toLikeCriteria(key, value)); + } + } else { + query.addCriteria(toLikeCriteria(key, value)); + } + } else { + try { + UUID uuid = UUID.fromString(value); + query.addCriteria(toUuidCriteria(key, uuid)); + } catch (Exception var9) { + query.addCriteria(toLikeCriteria(key, value)); + } + } + } else { + try { + int version = Integer.parseInt(value); + query.addCriteria(Criteria.where(key).is(version)); + } catch (Exception var11) { + } + } + } else if (jValue.isJsonArray() && !key.equals("sites.groupUuid")) { + JsonArray jItems = jValue.getAsJsonArray(); + if (jItems.size() >= 0) { + query.addCriteria(toOrCriteria(key, jValue.getAsJsonArray())); + } else { + query.addCriteria(Criteria.where(key).exists(false)); + } + } else if (jValue.isJsonNull() && !key.equals("sites.groupUuid")) { + query.addCriteria(toEmptyCriteria(key)); + } + } + + } + + public static Criteria toCriteria(String jFilter) { + return Strings.isNullOrEmpty(jFilter) ? new Criteria() : toCriteria(McJsonUtils.toJsonElement(jFilter).getAsJsonObject()); + } + + public static Criteria toCriteria(JsonObject jFilter) { + if (jFilter.size() == 0) { + return new Criteria(); + } else { + List criterias = new ArrayList(); + + for(Map.Entry entry : jFilter.entrySet()) { + String key = (String)entry.getKey(); + JsonElement jValue = (JsonElement)entry.getValue(); + if (jValue.isJsonPrimitive()) { + String value = jValue.getAsString(); + if (Strings.isNullOrEmpty(value)) { + criterias.add(Criteria.where(key).exists(false)); + } else if (key.equals("sites.siteUuid")) { + Criteria criElem = toUuidCriteria("siteUuid", UUID.fromString(value)); + if (jFilter.has("sites.groupUuid")) { + JsonElement jGroups = jFilter.get("sites.groupUuid"); + if (jGroups.isJsonNull()) { + criElem.and("groupUuid").exists(false); + } else if (jGroups.isJsonArray()) { + criElem.andOperator(new Criteria[]{toOrCriteria("groupUuid", jGroups.getAsJsonArray())}); + } + } + + criterias.add(Criteria.where("sites").elemMatch(criElem)); + } else if (!key.endsWith("versionCode") && !key.endsWith("SdkVersion")) { + try { + UUID uuid = UUID.fromString(value); + criterias.add(Criteria.where(key).is(uuid)); + } catch (Exception var13) { + criterias.add(Criteria.where(key).regex(escapedPattern(value))); + } + } else { + criterias.add(Criteria.where(key).is(jValue.getAsLong())); + } + } else if (jValue.isJsonArray() && !key.equals("sites.groupUuid")) { + JsonArray jItems = jValue.getAsJsonArray(); + if (jItems.size() <= 0) { + criterias.add(Criteria.where(key).exists(false)); + } else { + List subCriterias = new ArrayList(); + + for(JsonElement jItem : jItems) { + if (!jItem.isJsonNull()) { + String item = jItem.getAsString(); + + try { + UUID uuid = UUID.fromString(item); + subCriterias.add(Criteria.where(key).is(uuid)); + } catch (Exception var12) { + subCriterias.add(Criteria.where(key).regex(escapedPattern(item))); + } + } + } + + if (!subCriterias.isEmpty()) { + criterias.add((new Criteria()).orOperator((Criteria[])subCriterias.toArray(new Criteria[0]))); + } + } + } else if (jValue.isJsonNull() && !key.equals("sites.groupUuid")) { + criterias.add(Criteria.where(key).exists(false)); + } + } + + return (new Criteria()).andOperator((Criteria[])criterias.toArray(new Criteria[0])); + } + } + + public static Pattern escapedPattern(String value) { + return Pattern.compile(Pattern.quote(value), 66); + } + + public static Criteria toLikeCriteria(String key, String regex) { + return Criteria.where(key).regex(escapedPattern(regex)); + } + + public static Criteria toOrCriteria(String key, JsonArray jArray) { + Criteria criteria = new Criteria(); + List subCriterias = new ArrayList(); + + for(JsonElement jElement : jArray) { + if (!jElement.isJsonNull()) { + String value = jElement.getAsString(); + + try { + UUID uuid = UUID.fromString(value); + subCriterias.add(toUuidCriteria(key, uuid)); + } catch (Exception var8) { + subCriterias.add(toLikeCriteria(key, value)); + } + } + } + + if (subCriterias.size() > 0) { + criteria.orOperator((Criteria[])subCriterias.toArray(new Criteria[0])); + } + + return criteria; + } + + public static Criteria toUuidCriteria(String key, UUID uuid) { + return Criteria.where(key).is(uuid); + } + + public static Criteria toEmptyCriteria(String key) { + return Criteria.where(key).exists(false); + } + + public static LongSupplier toTotalSupplier(final long total) { + return new LongSupplier() { + public long getAsLong() { + return total; + } + }; + } + + public static void createIndex(MongoTemplate mongoTemplate, String collectionName, Document keys, String indexName, Boolean isUnique, Long expireAfter) { + MongoCollection collection = mongoTemplate.collectionExists(collectionName) ? mongoTemplate.getCollection(collectionName) : mongoTemplate.createCollection(collectionName); + IndexOptions options = new IndexOptions(); + if (!Strings.isNullOrEmpty(indexName)) { + options.name(indexName); + } + + if (isUnique != null) { + options.unique(isUnique); + } + + if (expireAfter != null) { + options.expireAfter(expireAfter, TimeUnit.SECONDS); + } + + Set keySet = keys.keySet(); + ListIndexesIterable indexes = collection.listIndexes(); + if (indexes != null) { + Document curIndex = null; + MongoCursor var11 = indexes.iterator(); + + while(var11.hasNext()) { + Document index = (Document)var11.next(); + Document keyMap = (Document)index.get("key", Document.class); + Set sets = keyMap.keySet(); + if (sets.equals(keySet)) { + curIndex = index; + break; + } + } + + if (curIndex != null) { + boolean isSame = true; + if (isUnique == null) { + if (curIndex.containsKey("unique")) { + isSame = false; + } + } else if (!curIndex.containsKey("unique") || !curIndex.get("unique").equals(isUnique)) { + isSame = false; + } + + if (expireAfter == null) { + if (curIndex.containsKey("expireAfterSeconds")) { + isSame = false; + } + } else if (!curIndex.containsKey("expireAfterSeconds") || !curIndex.get("expireAfterSeconds").equals(expireAfter)) { + isSame = false; + } + + if (isSame) { + return; + } + + collection.dropIndex((String)curIndex.get("name")); + } + } + + collection.createIndex(keys, options); + } + + public static void dropIndex(MongoTemplate mongoTemplate, String collectionName, String... fields) { + if (mongoTemplate.collectionExists(collectionName)) { + MongoCollection collection = mongoTemplate.getCollection(collectionName); + ListIndexesIterable indexes = collection.listIndexes(); + if (indexes != null) { + Set keySet = Sets.newHashSet(fields); + MongoCursor var6 = indexes.iterator(); + + while(var6.hasNext()) { + Document index = (Document)var6.next(); + Document keyMap = (Document)index.get("key", Document.class); + if (keyMap.keySet().equals(keySet)) { + collection.dropIndex(index.getString("name")); + break; + } + } + } + + } + } +} diff --git a/src/main/java/com/mitac/cell/db/util/McPipeLine.java b/src/main/java/com/mitac/cell/db/util/McPipeLine.java new file mode 100644 index 0000000..f9866d8 --- /dev/null +++ b/src/main/java/com/mitac/cell/db/util/McPipeLine.java @@ -0,0 +1,4 @@ +package com.mitac.cell.db.util; + +public class McPipeLine { +} diff --git a/src/main/java/com/mitac/cell/doc/Csv.java b/src/main/java/com/mitac/cell/doc/Csv.java new file mode 100644 index 0000000..36a7cb1 --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/Csv.java @@ -0,0 +1,214 @@ +package com.mitac.cell.doc; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class Csv { + private final char separator; + private final char quoteChar; + private final char escapeChar; + private final boolean strictQuotes; + private boolean inToken; + private final boolean ignoreLeadingWhiteSpace; + public static final char DEFAULT_SEPARATOR = ','; + public static final char DEFAULT_QUOTE_CHARACTER = '"'; + public static final char DEFAULT_ESCAPE_CHARACTER = '\\'; + public static final char NULL_CHARACTER = '\u0000'; + public static final String DEFAULT_LINE_END = "\n"; + public static final char NO_QUOTE_CHARACTER = '\u0000'; + public static final char NO_ESCAPE_CHARACTER = '\u0000'; + + public Csv() { + this(',', '"', '\\'); + } + + public Csv(char separator) { + this(separator, '"', '\\'); + } + + public Csv(char separator, char quoteChar) { + this(separator, quoteChar, '\\'); + } + + public Csv(char separator, char quoteChar, char escape) { + this(separator, quoteChar, escape, false); + } + + public Csv(char separator, char quoteChar, char escape, boolean strictQuotes) { + this(separator, quoteChar, escape, strictQuotes, true, "\n"); + } + + public Csv(char separator, char quoteChar, char escape, boolean strictQuotes, boolean ignoreLeadingWhiteSpace, String lineEnd) { + this.inToken = false; + if (this.anyCharactersAreTheSame(separator, quoteChar, escape)) { + throw new UnsupportedOperationException("The separator, quote character, and escape character must be different!"); + } else if (separator == 0) { + throw new UnsupportedOperationException("The separator character can't be null!"); + } else { + this.separator = separator; + this.quoteChar = quoteChar; + this.escapeChar = escape; + this.strictQuotes = strictQuotes; + this.ignoreLeadingWhiteSpace = ignoreLeadingWhiteSpace; + } + } + + private boolean anyCharactersAreTheSame(char separator, char quoteChar, char escape) { + return this.isSameCharacter(separator, quoteChar) || this.isSameCharacter(separator, escape) || this.isSameCharacter(quoteChar, escape); + } + + private boolean isSameCharacter(char c1, char c2) { + return c1 != 0 && c1 == c2; + } + + public String[] parse(String csvText) throws IOException { + if (csvText == null) { + return null; + } else { + List tokenList = new ArrayList(); + StringBuilder sb = new StringBuilder(); + boolean inQuotes = false; + + for(int i = 0; i < csvText.length(); ++i) { + char c = csvText.charAt(i); + if (c == this.escapeChar) { + if (this.isNextCharacterEscapable(csvText, inQuotes || this.inToken, i)) { + sb.append(csvText.charAt(i + 1)); + ++i; + } + } else if (c == this.quoteChar) { + if (this.isNextCharacterEscapedQuote(csvText, inQuotes || this.inToken, i)) { + sb.append(csvText.charAt(i + 1)); + ++i; + } else { + if (!this.strictQuotes && i > 2 && csvText.charAt(i - 1) != this.separator && csvText.length() > i + 1 && csvText.charAt(i + 1) != this.separator) { + if (this.ignoreLeadingWhiteSpace && sb.length() > 0 && this.isAllWhiteSpace(sb)) { + sb.setLength(0); + } else { + sb.append(c); + } + } + + inQuotes = !inQuotes; + } + + this.inToken = !this.inToken; + } else if (c == this.separator && !inQuotes) { + tokenList.add(sb.toString()); + sb.setLength(0); + this.inToken = false; + } else if (!this.strictQuotes || inQuotes) { + sb.append(c); + this.inToken = true; + } + } + + if (sb != null) { + tokenList.add(sb.toString()); + } + + return (String[])tokenList.toArray(new String[tokenList.size()]); + } + } + + private boolean isNextCharacterEscapedQuote(String csvText, boolean inQuotes, int i) { + int nextIndex = i + 1; + return inQuotes && csvText.length() > nextIndex && csvText.charAt(nextIndex) == this.quoteChar; + } + + protected boolean isNextCharacterEscapable(String csvText, boolean inQuotes, int i) { + int nextIndex = i + 1; + char nextChar = csvText.charAt(nextIndex); + return inQuotes && csvText.length() > nextIndex && (nextChar == this.quoteChar || csvText.charAt(nextIndex) == this.escapeChar); + } + + protected boolean isAllWhiteSpace(CharSequence sb) { + boolean result = true; + + for(int i = 0; i < sb.length(); ++i) { + char c = sb.charAt(i); + if (!Character.isWhitespace(c)) { + result = false; + break; + } + } + + return result; + } + + public String toString(String[] columns) { + StringBuilder sb = new StringBuilder(); + + for(int i = 0; i < columns.length; ++i) { + if (i != 0) { + sb.append(this.separator); + } + + String nextElement = columns[i]; + if (nextElement != null) { + if (this.quoteChar != 0) { + sb.append(this.quoteChar); + } + + sb.append((CharSequence)(this.stringContainsSpecialCharacters(nextElement) ? this.processLine(nextElement) : nextElement)); + if (this.quoteChar != 0) { + sb.append(this.quoteChar); + } + } + } + + return sb.toString(); + } + + public String toString(Object[] columns) { + List list = new ArrayList(); + + for(Object obj : columns) { + list.add(obj.toString()); + } + + return this.toString(list); + } + + public String toString(ArrayList columns) { + List list = new ArrayList(); + + for(Object obj : columns) { + list.add(obj.toString()); + } + + return this.toString(list); + } + + public String toString(Set columns) { + List list = new ArrayList(columns); + return this.toString(list); + } + + public String toString(List columns) { + return this.toString((String[])columns.toArray()); + } + + private boolean stringContainsSpecialCharacters(String line) { + return line.indexOf(this.quoteChar) != -1 || line.indexOf(this.escapeChar) != -1; + } + + protected StringBuilder processLine(String nextElement) { + StringBuilder sb = new StringBuilder(); + + for(int j = 0; j < nextElement.length(); ++j) { + char nextChar = nextElement.charAt(j); + if (this.escapeChar != 0 && nextChar == this.quoteChar) { + sb.append(this.escapeChar).append(nextChar); + } else if (this.escapeChar != 0 && nextChar == this.escapeChar) { + sb.append(this.escapeChar).append(nextChar); + } else { + sb.append(nextChar); + } + } + + return sb; + } +} diff --git a/src/main/java/com/mitac/cell/doc/CsvReader.java b/src/main/java/com/mitac/cell/doc/CsvReader.java new file mode 100644 index 0000000..72dcfd1 --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/CsvReader.java @@ -0,0 +1,51 @@ +package com.mitac.cell.doc; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public abstract class CsvReader { + private BufferedReader reader; + + public CsvReader(String path) throws FileNotFoundException { + this(new File(path)); + } + + public CsvReader(File file) { + try { + this.reader = new BufferedReader(new FileReader(file)); + } catch (FileNotFoundException var3) { + } + + } + + public CsvReader(InputStream input) { + this.reader = new BufferedReader(new InputStreamReader(input)); + } + + public abstract void onNewRow(int var1, String[] var2); + + public void onEnd() { + } + + public void parseAll() { + try { + int lineNum = 0; + + String line; + while((line = this.reader.readLine()) != null) { + String[] row = (new Csv()).parse(line); + this.onNewRow(lineNum++, row); + } + + this.reader.close(); + this.onEnd(); + } catch (IOException var4) { + } + + } +} diff --git a/src/main/java/com/mitac/cell/doc/ExcelCell.java b/src/main/java/com/mitac/cell/doc/ExcelCell.java new file mode 100644 index 0000000..d82feea --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/ExcelCell.java @@ -0,0 +1,71 @@ +package com.mitac.cell.doc; + +import com.google.common.base.CharMatcher; +import com.google.common.base.Strings; +import com.mitac.cell.utils.McNumberUtils; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; + +public class ExcelCell { + public int columnIndex; + public int rowIndex; + public String cellName; + public String value; + + public ExcelCell(String cellName, String value) { + this.cellName = cellName; + this.value = value; + this.columnIndex = this.getColumnIndex(cellName); + this.rowIndex = this.getRowIndex(cellName); + } + + public String getColumnName() { + return CharMatcher.inRange('0', '9').removeFrom(this.cellName); + } + + public int getColumnIndex() { + return this.columnIndex; + } + + private int getRowIndex(String cellName) { + return Integer.parseInt(CharMatcher.inRange('0', '9').retainFrom(cellName)) - 1; + } + + private int getColumnIndex(String cellName) { + String columnName = CharMatcher.inRange('0', '9').removeFrom(cellName).toUpperCase(); + String reversedName = (new StringBuffer(columnName)).reverse().toString(); + int index = 0; + + for(int i = 0; i < reversedName.length(); ++i) { + int n = reversedName.charAt(i) - 65; + index += i == 0 ? n : 0 + i * 26 * (n + 1); + } + + return index; + } + + public String toString() { + return this.value; + } + + public int toInteger() { + return McNumberUtils.toInt(this.value); + } + + public float toFloat() { + return McNumberUtils.toFloat(this.value); + } + + public static boolean isEmpty(Cell cell) { + if (cell == null) { + return true; + } else { + CellType cellType = cell.getCellType(); + if (cellType != CellType._NONE && cellType != CellType.BLANK) { + return cellType == CellType.STRING ? Strings.isNullOrEmpty(cell.getStringCellValue().trim()) : false; + } else { + return true; + } + } + } +} diff --git a/src/main/java/com/mitac/cell/doc/ExcelReader.java b/src/main/java/com/mitac/cell/doc/ExcelReader.java new file mode 100644 index 0000000..416ceec --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/ExcelReader.java @@ -0,0 +1,184 @@ +package com.mitac.cell.doc; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.exceptions.OpenXML4JException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.xssf.eventusermodel.XSSFReader; +import org.apache.poi.xssf.model.SharedStrings; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +public abstract class ExcelReader { + private XMLReader xmlReader; + private XSSFReader xssfReader; + + public ExcelReader(String path) { + try { + OPCPackage pkg = OPCPackage.open(path); + this.setPackage(pkg); + } catch (InvalidFormatException e) { + e.printStackTrace(); + } + + } + + public ExcelReader(File file) { + try { + OPCPackage pkg = OPCPackage.open(file); + this.setPackage(pkg); + } catch (InvalidFormatException e) { + e.printStackTrace(); + } + + } + + public ExcelReader(InputStream is) { + try { + OPCPackage pkg = OPCPackage.open(is); + this.setPackage(pkg); + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private void setPackage(OPCPackage pkg) { + try { + this.xssfReader = new XSSFReader(pkg); + SharedStrings stringsTable = this.xssfReader.getSharedStringsTable(); + this.xmlReader = this.fetchSheetParser(stringsTable); + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (OpenXML4JException e) { + e.printStackTrace(); + } + + } + + public void parceSheet(String sheetName) { + try { + InputStream sheetIS = this.xssfReader.getSheet(sheetName); + InputSource sheetSource = new InputSource(sheetIS); + this.xmlReader.parse(sheetSource); + sheetIS.close(); + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } + + } + + public void parseAll() { + try { + Iterator sheets = this.xssfReader.getSheetsData(); + + while(sheets.hasNext()) { + InputStream is = (InputStream)sheets.next(); + InputSource sheetSource = new InputSource(is); + this.xmlReader.parse(sheetSource); + is.close(); + } + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } + + } + + public XMLReader fetchSheetParser(SharedStrings stringsTable) { + XMLReader xmlReader = this.xmlReader(); + ContentHandler handler = new SheetHandler(stringsTable); + xmlReader.setContentHandler(handler); + return xmlReader; + } + + public XMLReader xmlReader() { + SAXParserFactory parserFactory = SAXParserFactory.newInstance(); + + try { + return parserFactory.newSAXParser().getXMLReader(); + } catch (SAXException | ParserConfigurationException e) { + ((Exception)e).printStackTrace(); + return null; + } + } + + public abstract void onSheetDataStart(); + + public abstract boolean onNewRow(ExcelRow var1); + + public abstract void onSheetDataEnd(); + + private class SheetHandler extends DefaultHandler { + private static final String CELL_NUM = "r"; + private static final String CELL_TYPE = "t"; + private SharedStrings stringsTable; + private ExcelRow row = null; + private String curCellName = null; + private String curCellType = null; + private String curCellValue; + + private SheetHandler(SharedStrings stringsTable) { + this.stringsTable = stringsTable; + } + + public void startElement(String uri, String localName, String name, Attributes attributes) { + if (name.equals("row")) { + this.row = new ExcelRow(); + } else if (name.equals("c")) { + this.curCellValue = ""; + this.curCellName = attributes.getValue("r"); + this.curCellType = attributes.getValue("t"); + } else if (name.equals("sheetData")) { + ExcelReader.this.onSheetDataStart(); + } + + } + + public void endElement(String uri, String localName, String name) { + if (name.equals("row")) { + ExcelReader.this.onNewRow(this.row); + } else if (name.equals("c")) { + if (this.isStringCell()) { + int idx = Integer.parseInt(this.curCellValue); + this.curCellValue = this.stringsTable.getItemAt(idx).getString(); + this.curCellType = null; + } + + this.row.addCell(this.curCellName, this.curCellValue); + } else if (name.equals("sheetData")) { + ExcelReader.this.onSheetDataEnd(); + } + + } + + public void characters(char[] ch, int start, int length) { + String var10001 = this.curCellValue; + this.curCellValue = var10001 + new String(ch, start, length); + } + + private boolean isStringCell() { + return this.curCellType != null && this.curCellType.equals("s"); + } + } +} diff --git a/src/main/java/com/mitac/cell/doc/ExcelRow.java b/src/main/java/com/mitac/cell/doc/ExcelRow.java new file mode 100644 index 0000000..e44a6a7 --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/ExcelRow.java @@ -0,0 +1,51 @@ +package com.mitac.cell.doc; + +import java.util.HashMap; +import java.util.Iterator; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; + +public class ExcelRow extends HashMap { + private static final long serialVersionUID = -2035806587539130093L; + + public void addCell(String cellName, String value) { + ExcelCell cell = new ExcelCell(cellName, value); + this.put(cell.columnIndex, cell); + } + + public int getRowIndex() { + return this.size() > 0 ? ((ExcelCell)this.get(0)).rowIndex : -1; + } + + public String getString(int columnIndex) { + ExcelCell cell = (ExcelCell)this.get(columnIndex); + return cell == null ? "" : cell.toString(); + } + + public int getInteger(int columnIndex) { + ExcelCell cell = (ExcelCell)this.get(columnIndex); + return cell == null ? 0 : cell.toInteger(); + } + + public float getFloat(int columnIndex) { + ExcelCell cell = (ExcelCell)this.get(columnIndex); + return cell == null ? 0.0F : cell.toFloat(); + } + + public static boolean isEmpty(Row row) { + if (row != null && row.getPhysicalNumberOfCells() != 0) { + Iterator it = row.cellIterator(); + + while(it.hasNext()) { + Cell cell = (Cell)it.next(); + if (!ExcelCell.isEmpty(cell)) { + return false; + } + } + + return true; + } else { + return true; + } + } +} diff --git a/src/main/java/com/mitac/cell/doc/ExcelWriter.java b/src/main/java/com/mitac/cell/doc/ExcelWriter.java new file mode 100644 index 0000000..2e24341 --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/ExcelWriter.java @@ -0,0 +1,783 @@ +package com.mitac.cell.doc; + +import com.google.common.base.Strings; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; +import javax.imageio.ImageIO; +import org.apache.poi.hssf.usermodel.HSSFDataFormat; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; +import org.apache.poi.ooxml.POIXMLProperties; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.ClientAnchor; +import org.apache.poi.ss.usermodel.Color; +import org.apache.poi.ss.usermodel.ConditionalFormattingRule; +import org.apache.poi.ss.usermodel.CreationHelper; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.FontFormatting; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.PatternFormatting; +import org.apache.poi.ss.usermodel.Picture; +import org.apache.poi.ss.usermodel.RichTextString; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.SheetConditionalFormatting; +import org.apache.poi.ss.usermodel.VerticalAlignment; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.XSSFClientAnchor; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.bouncycastle.util.encoders.Hex; + +public class ExcelWriter { + public static final String INTEGER_COMMA_FORMAT = "#,##0"; + public static final String FLOAT_COMMA_FORMAT = "#,##0.00"; + private XSSFWorkbook workbook; + private POIXMLProperties properties; + private CreationHelper createHelper; + private Sheet activeSheet; + Map fontMap; + Map styleMap; + private CellStyle tempStyle; + + public ExcelWriter() { + this((InputStream)null); + } + + public ExcelWriter(File input) throws FileNotFoundException { + this((InputStream)(new FileInputStream(input))); + } + + public ExcelWriter(InputStream input) { + this.fontMap = new HashMap(); + this.styleMap = new HashMap(); + + try { + this.workbook = input == null ? new XSSFWorkbook() : new XSSFWorkbook(input); + this.init(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private void init() { + this.properties = this.workbook.getProperties(); + this.createHelper = this.workbook.getCreationHelper(); + this.tempStyle = this.workbook.createCellStyle(); + this.initActiveSheet(); + } + + public void close() { + try { + this.workbook.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public POIXMLProperties.CoreProperties getCoreProperty() { + return this.properties.getCoreProperties(); + } + + public POIXMLProperties.CustomProperties getCustomProperty() { + return this.properties.getCustomProperties(); + } + + public int getNumberOfSheets() { + return this.workbook.getNumberOfSheets(); + } + + public int getActiveSheetIndex() { + return this.workbook.getActiveSheetIndex(); + } + + public Sheet getSheet(int index) { + return this.workbook.getSheetAt(index); + } + + public Sheet addSheet(String sheetName) { + this.activeSheet = Strings.isNullOrEmpty(sheetName) ? this.workbook.createSheet() : this.workbook.createSheet(sheetName); + this.setActive(this.activeSheet); + return this.activeSheet; + } + + public void removeSheet(int index) { + if (index >= 0 && index < this.getNumberOfSheets()) { + this.workbook.removeSheetAt(index); + } + + } + + public void removeSheet(String... sheetNames) { + for(String sheetName : sheetNames) { + int sheetIndex = this.workbook.getSheetIndex(sheetName); + if (sheetIndex >= 0) { + this.removeSheet(sheetIndex); + } + } + + } + + public void setColumns(String... names) { + this.setRow(0, (Object[])names); + this.activeSheet.createFreezePane(0, 1); + } + + public void setColumns(int rowNum, String... names) { + this.setRow(rowNum, (Object[])names); + this.activeSheet.createFreezePane(0, 1); + } + + public void freezeRows(int rowNum) { + this.freeze(rowNum, 0); + } + + public void freeze(int rowNum, int colNum) { + this.activeSheet.createFreezePane(colNum, rowNum); + } + + public void setAutoSizeColumn(int colIndex) { + int orgWidth = this.activeSheet.getColumnWidth(colIndex); + this.activeSheet.autoSizeColumn(colIndex); + float newWidth = (float)this.activeSheet.getColumnWidth(colIndex); + if (newWidth < (float)orgWidth) { + this.activeSheet.setColumnWidth(colIndex, orgWidth); + } + + } + + public void setAutoSizeColumns() { + this.setAutoSizeColumns(0, this.getLastColIndex()); + } + + public void setAutoSizeColumns(int colFrom, int colTo) { + for(int i = colFrom; i <= colTo; ++i) { + this.setAutoSizeColumn(i); + } + + } + + public void setAutoSizeColumns(int... colIndexes) { + for(int colIndex : colIndexes) { + this.setAutoSizeColumn(colIndex); + } + + } + + public void setColumnFormat(int colIndex, short formatNo) { + CellStyle style = this.workbook.createCellStyle(); + style.setDataFormat(formatNo); + this.activeSheet.setDefaultColumnStyle(colIndex, style); + } + + public void setColumnFormat(int colIndex, String format) { + short formatNo = this.createHelper.createDataFormat().getFormat(format); + this.setColumnFormat(colIndex, formatNo); + } + + public Row getRow(int rowNo) { + Row row = this.activeSheet.getRow(rowNo); + if (row == null) { + row = this.activeSheet.createRow(rowNo); + } + + return row; + } + + public Cell getCell(int rowNo, int colNo) { + return this.getCell(this.getRow(rowNo), colNo); + } + + public Cell getCell(Row row, int colNo) { + Cell cell = row.getCell(colNo); + if (cell == null) { + cell = row.createCell(colNo); + } + + return cell; + } + + public CellStyle getCellStyle(int rowNo, int colNo) { + return this.getCell(rowNo, colNo).getCellStyle(); + } + + public void setRow(int rowNo, Object... values) { + Row row = this.getRow(rowNo); + + for(int i = 0; i < values.length; ++i) { + Object value = values[i]; + if (value != null) { + this.setCell(this.getCell(row, i), value); + } + } + + } + + private void initActiveSheet() { + int index = this.getActiveSheetIndex(); + this.activeSheet = this.workbook.getSheetAt(index); + } + + public Sheet getActiveSheet() { + if (this.activeSheet == null) { + this.initActiveSheet(); + } + + return this.activeSheet; + } + + public boolean setActive(int sheetIndex) { + if (sheetIndex >= 0 && sheetIndex < this.getNumberOfSheets()) { + this.activeSheet = this.workbook.getSheetAt(sheetIndex); + this.workbook.setActiveSheet(sheetIndex); + this.workbook.setSelectedTab(sheetIndex); + return true; + } else { + return false; + } + } + + public boolean setActive(String name) { + this.activeSheet = this.workbook.getSheet(name); + return this.setActive(this.activeSheet); + } + + public boolean setActive(Sheet sheet) { + return this.setActive(this.workbook.getSheetIndex(sheet)); + } + + public Sheet getSheet(String sheetName) { + return this.workbook.getSheet(sheetName); + } + + public void changeSheet(String oldName, String newName) { + int index = this.workbook.getSheetIndex(oldName); + if (index >= 0) { + this.workbook.setSheetName(index, newName); + } + + } + + public void changeSheet(int index, String newName) { + if (index >= 0) { + this.workbook.setSheetName(index, newName); + } + + } + + public void setCell(String cellId, Object value) { + this.setCell(this.getCell(cellId), value); + } + + public void setCell(int rowNo, int colNo, Object value) { + this.setCell(rowNo, colNo, value, (CellStyle)null); + } + + public void setCell(int rowNo, int colNo, Object value, CellStyle style) { + Row row = this.activeSheet.getRow(rowNo); + if (row == null) { + row = this.activeSheet.createRow(rowNo); + } + + Cell cell = row.getCell(colNo); + if (cell == null) { + cell = row.createCell(colNo); + } + + this.setCell(cell, value, style); + } + + public CellStyle newCellStyle() { + return this.workbook.createCellStyle(); + } + + public CellStyle clone(CellStyle style) { + CellStyle newStyle = this.newCellStyle(); + newStyle.cloneStyleFrom(style); + return newStyle; + } + + public CreationHelper getCreationHelper() { + return this.workbook.getCreationHelper(); + } + + public short getCustomDataFormat(String format) { + return this.getCreationHelper().createDataFormat().getFormat(format); + } + + public void setCell(Cell cell, Object value) { + this.setCell(cell, value, (CellStyle)null); + } + + public void setCell(Cell cell, Object value, CellStyle style) { + this.setCell(cell, value, style, (String)null, (String)null, (String)null, (String)null); + } + + public void setFileSizeCell(int rowNo, int colNo, long value, CellStyle style) { + String format; + float size; + if (value > 1099511627776L) { + size = (float)value / 1.0995116E12F; + format = "#,##0.00\" TB\""; + } else if (value > 1073741824L) { + size = (float)value / 1.0737418E9F; + format = "#,##0.00\" GB\""; + } else if (value > 1048576L) { + size = (float)value / 1048576.0F; + format = "#,##0.00\" MB\""; + } else if (value > 1024L) { + size = (float)value / 1024.0F; + format = "#,##0.00\" KB\""; + } else if (value > 0L) { + size = (float)value; + format = "0\" bytes\""; + } else { + size = 0.0F; + format = "0"; + } + + this.setCell(this.getCell(rowNo, colNo), size, style, format, (String)null, (String)null, (String)null); + } + + public void setCell(int rowIndex, int colIndex, Object value, CellStyle style, String format, String hAlignment, String vAlignment, String colorName) { + this.setCell(this.getCell(rowIndex, colIndex), value, style, format, hAlignment, vAlignment, colorName); + } + + public void setCell(Cell cell, Object value, CellStyle style, String format, String hAlignment, String vAlignment, String colorName) { + if (cell != null) { + if (style == null) { + style = cell.getCellStyle(); + } + + if (style != null) { + this.tempStyle.cloneStyleFrom(style); + } + + if (format == null) { + if (value instanceof Number) { + if (!(value instanceof Integer) && !(value instanceof Long)) { + this.tempStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + } else { + this.tempStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0")); + } + } + } else if (!format.isEmpty()) { + this.tempStyle.setDataFormat(this.getCustomDataFormat(format)); + } + + if (!Strings.isNullOrEmpty(colorName)) { + int fontIndex = style == null ? 0 : style.getFontIndex(); + this.workbook.getFontAt(fontIndex); + this.tempStyle.setFont(this.getFont(style, colorName)); + } + + if (!Strings.isNullOrEmpty(hAlignment)) { + this.tempStyle.setAlignment(HorizontalAlignment.valueOf(hAlignment.toUpperCase())); + } + + if (!Strings.isNullOrEmpty(vAlignment)) { + this.tempStyle.setVerticalAlignment(VerticalAlignment.valueOf(vAlignment.toUpperCase())); + } + + this.setCellStyle(cell, this.tempStyle); + if (value == null) { + this.removeCell(cell); + } else if (value instanceof Character) { + cell.setCellValue(Character.toString((Character)value)); + } else if (value instanceof String) { + if (Strings.isNullOrEmpty((String)value)) { + this.removeCell(cell); + } else { + cell.setCellValue((String)value); + } + } else if (value instanceof Number) { + this.tempStyle.setAlignment(HorizontalAlignment.RIGHT); + this.setCellStyle(cell, this.tempStyle); + cell.setCellValue(((Number)value).doubleValue()); + } else if (value instanceof Date) { + cell.setCellValue((Date)value); + } else if (value instanceof Boolean) { + cell.setCellValue((Boolean)value); + } else if (value instanceof RichTextString) { + cell.setCellValue((RichTextString)value); + } + + } + } + + private void setCellStyle(Cell cell, CellStyle style) { + String styleId = this.cellStyleId(style); + if (this.styleMap.containsKey(styleId)) { + style = (CellStyle)this.styleMap.get(styleId); + } else { + style = this.clone(style); + this.styleMap.put(styleId, style); + } + + cell.setCellStyle(style); + } + + public void setSell(Cell cell, Date date, CellStyle style, String dateFormat) { + style.setDataFormat(this.getCustomDataFormat(dateFormat)); + } + + public XSSFFont getFont(CellStyle style) { + return this.workbook.getFontAt(style.getFontIndex()); + } + + public XSSFFont getFont(CellStyle style, String colorName) { + XSSFFont cellFont = this.getFont(style); + return Strings.isNullOrEmpty(colorName) ? cellFont : this.getFont(cellFont.getFontName(), cellFont.getFontHeightInPoints(), colorName, cellFont.getBold(), cellFont.getItalic(), cellFont.getUnderline(), cellFont.getStrikeout()); + } + + public XSSFFont getFont(CellStyle style, String colorName, boolean bold, boolean italic, byte underline, boolean strike) { + XSSFFont cellFont = this.getFont(style); + return this.getFont(cellFont.getFontName(), cellFont.getFontHeightInPoints(), colorName, cellFont.getBold(), cellFont.getItalic(), cellFont.getUnderline(), cellFont.getStrikeout()); + } + + public XSSFFont getFont(String fontName, short size, String colorName, boolean bold, boolean italic, byte underline, boolean strike) { + String key = fontName + size + colorName + bold + italic + underline + strike; + if (this.fontMap.containsKey(key)) { + return (XSSFFont)this.fontMap.get(key); + } else { + XSSFFont font = this.workbook.createFont(); + font.setFontName(fontName); + font.setFontHeightInPoints(size); + font.setBold(bold); + font.setUnderline(underline); + font.setItalic(italic); + font.setStrikeout(strike); + font.setColor(this.toColor(colorName)); + this.fontMap.put(key, font); + return font; + } + } + + public void setFormula(Cell cell, String formular, String format, CellStyle style, String alignment) { + style = this.clone(style); + style.setDataFormat(HSSFDataFormat.getBuiltinFormat(format)); + if (!Strings.isNullOrEmpty(alignment)) { + style.setAlignment(HorizontalAlignment.valueOf(alignment.toUpperCase())); + } + + this.setCellStyle(cell, style); + cell.setCellFormula(formular); + this.evalueateFormula(cell); + } + + private void evalueateFormula(Cell cell) { + this.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell); + } + + public void setSumToCells(int writeRowNum, String[] colChars, int startNum, int endNum, CellStyle style, String alignment) { + for(String colChar : colChars) { + int colIndex = 0; + int power = 0; + + for(int i = colChar.length() - 1; i >= 0; --i) { + Character ch = colChar.charAt(i); + if (ch < 'A' || ch > 'Z') { + return; + } + + colIndex = (int)((double)colIndex + (power == 0 ? (double)ch.compareTo('A') : (double)(ch.compareTo('A') + 1) * Math.pow((double)26.0F, (double)power))); + ++power; + } + + Cell cell = this.getCell(writeRowNum, colIndex); + String strFormula = String.format("SUM(%s%d:%s%d)", colChar, startNum, colChar, endNum); + this.setFormula(cell, strFormula, "#,##0", style, alignment); + } + + } + + public void addImage(InputStream input, int x, int y, int width, int height) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + try { + BufferedImage image = ImageIO.read(input); + ImageIO.write(image, "png", bos); + int imageId = this.workbook.addPicture(bos.toByteArray(), 6); + bos.close(); + Drawing drawing = this.activeSheet.createDrawingPatriarch(); + ClientAnchor anchor = new XSSFClientAnchor(); + if (x > 0) { + anchor.setDx1(x); + } + + if (y > 0) { + anchor.setDy1(y); + } + + Picture picture = drawing.createPicture(anchor, imageId); + if (width > 0 && height > 0) { + double xScale = (double)(width / image.getWidth()); + double yScale = (double)(height / image.getHeight()); + picture.resize(xScale, yScale); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void fill(int rowFrom, int rowTo, int colFrom, int colTo, Object value, CellStyle cellStyle) { + for(int i = rowFrom; i <= rowTo; ++i) { + for(int j = colFrom; j <= colTo; ++j) { + this.setCell(i, j, value, cellStyle); + } + } + + } + + public int merge(int rowFrom, int rowTo, int colFrom, int colTo) { + return this.merge(rowFrom, rowTo, colFrom, colTo, (CellStyle)null); + } + + public int merge(int rowFrom, int rowTo, int colFrom, int colTo, CellStyle cellStyle) { + if (rowFrom == rowTo && colFrom == colTo) { + return -1; + } else { + CellRangeAddress cellRangeAddress = new CellRangeAddress(rowFrom, rowTo, colFrom, colTo); + int regionId = this.activeSheet.addMergedRegion(cellRangeAddress); + if (cellStyle != null) { + for(int row = rowFrom; row <= rowTo; ++row) { + for(int col = colFrom; col <= colTo; ++col) { + this.setCellStyle(this.getCell(row, col), cellStyle); + } + } + } + + return regionId; + } + } + + public void removeMergedRegion(int index) { + this.activeSheet.removeMergedRegion(index); + } + + public void removeCell(Cell cell) { + cell.getRow().removeCell(cell); + } + + public void insertColumns(int colAfter, int colNumbers) { + this.shiftColumns(colAfter, this.getLastColIndex(), colNumbers); + } + + public void removeColumns(int colFrom, int colTo) { + int mergedRegionNum = this.activeSheet.getNumMergedRegions(); + if (mergedRegionNum > 0) { + for(int i = 0; i < mergedRegionNum; ++i) { + CellRangeAddress range = this.activeSheet.getMergedRegion(i); + int colFirst = range.getFirstColumn(); + int colLast = range.getLastColumn(); + if (colFirst >= colFrom && colFirst <= colTo || colLast >= colFrom && colLast <= colTo) { + this.removeMergedRegion(i--); + --mergedRegionNum; + } + } + } + + for(Row row : this.activeSheet) { + for(int i = colFrom; i <= colTo; ++i) { + Cell cell = row.getCell(i); + if (cell != null) { + row.removeCell(cell); + } + } + } + + int lastColIndex = this.getLastColIndex(); + if (lastColIndex > colTo) { + this.shiftColumns(colTo + 1, lastColIndex, colFrom - colTo - 1); + } + + } + + public void removeRow(int rowIndex) { + this.activeSheet.removeRow(this.getRow(rowIndex)); + } + + public int getLastColIndex(int rowNum) { + return this.getRow(rowNum).getLastCellNum(); + } + + public int getLastColIndex() { + int colNum = 0; + + for(int i = 0; i < this.activeSheet.getLastRowNum(); ++i) { + Row row = this.activeSheet.getRow(i); + if (row != null) { + short rowColNum = row.getLastCellNum(); + if (rowColNum > colNum) { + colNum = rowColNum; + } + } + } + + return colNum - 1; + } + + public void shiftColumns(int colFrom, int colTo, int colNumbers) { + if (colFrom <= colTo && colNumbers != 0) { + int[] widths = new int[colTo - colFrom]; + + for(int i = 0; i < widths.length; ++i) { + widths[i] = this.activeSheet.getColumnWidth(i + colFrom); + } + + this.activeSheet.shiftColumns(colFrom, colTo, colNumbers); + + for(int i = 0; i < widths.length; ++i) { + this.activeSheet.setColumnWidth(i + colFrom + colNumbers, widths[i]); + } + + } + } + + public void addConditionalPattern(int rowFrom, int rowTo, int colFrom, int colTo, String formula, String textColor, String backgroundColor) { + SheetConditionalFormatting formatting = this.activeSheet.getSheetConditionalFormatting(); + ConditionalFormattingRule rule = formatting.createConditionalFormattingRule(formula); + if (!Strings.isNullOrEmpty(textColor)) { + FontFormatting font = rule.createFontFormatting(); + Color color = this.toColor(textColor); + font.setFontColor(color); + } + + if (!Strings.isNullOrEmpty(backgroundColor)) { + PatternFormatting fill = rule.createPatternFormatting(); + Color color = this.toColor(backgroundColor); + fill.setFillBackgroundColor(color); + fill.setFillPattern((short)1); + } + + CellRangeAddress[] ranges = new CellRangeAddress[]{new CellRangeAddress(rowFrom, rowTo, colFrom, colTo)}; + ConditionalFormattingRule[] rules = new ConditionalFormattingRule[]{rule}; + formatting.addConditionalFormatting(ranges, rules); + } + + public byte[] getBytes() { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + try { + this.workbook.write(bos); + bos.flush(); + byte[] bytes = bos.toByteArray(); + bos.close(); + return bytes; + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } + + public void setAutoFilter(int row) { + CellRangeAddress cellRange = new CellRangeAddress(row, row, 0, this.getLastColIndex()); + this.activeSheet.setAutoFilter(cellRange); + } + + public void write(OutputStream output) { + try { + this.workbook.write(output); + output.flush(); + output.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public Cell getCell(String cellId) { + if (Strings.isNullOrEmpty(cellId)) { + return null; + } else { + Pattern pattern = Pattern.compile("(?<=[\\w&&\\D])(?=\\d)"); + String[] tokens = pattern.split(cellId); + if (tokens.length != 0 && tokens.length <= 2) { + int rowNum = Integer.parseInt(tokens[1]); + int colNum = 0; + String colId = tokens[0].toLowerCase(); + + for(int i = 0; i < colId.length(); ++i) { + colNum = colNum * 26 + colId.charAt(i) - 97 + 1; + } + + Cell var10000; + if (rowNum >= 0 && colNum >= 0) { + --rowNum; + --colNum; + var10000 = this.getCell(rowNum, colNum); + } else { + var10000 = null; + } + + return var10000; + } else { + return null; + } + } + } + + private String cellStyleId(CellStyle style) { + StringBuilder sb = new StringBuilder(); + sb.append(style.getHidden()); + sb.append(style.getLocked()); + sb.append(style.getFontIndex()); + sb.append(style.getAlignment()); + sb.append(style.getVerticalAlignment()); + sb.append(style.getWrapText()); + sb.append(style.getQuotePrefixed()); + sb.append(style.getShrinkToFit()); + sb.append(style.getDataFormat()); + sb.append(style.getDataFormatString()); + sb.append(style.getIndention()); + sb.append(style.getRotation()); + sb.append(style.getBorderBottom()); + sb.append(style.getBorderLeft()); + sb.append(style.getBorderRight()); + sb.append(style.getBorderTop()); + sb.append(style.getBottomBorderColor()); + sb.append(style.getLeftBorderColor()); + sb.append(style.getRightBorderColor()); + sb.append(style.getTopBorderColor()); + sb.append(style.getFillBackgroundColor()); + sb.append(style.getFillBackgroundColorColor()); + sb.append(style.getFillForegroundColor()); + sb.append(style.getFillForegroundColorColor()); + sb.append(style.getFillPattern()); + return sb.toString(); + } + + private XSSFColor toColor(String colorName) { + byte[] bytes; + if (colorName.startsWith("#")) { + colorName = colorName.substring(1); + bytes = Hex.decode(colorName); + } else { + HSSFColor.HSSFColorPredefined color = HSSFColorPredefined.valueOf(colorName.toUpperCase()); + short[] rgb = color.getTriplet(); + bytes = new byte[]{(byte)rgb[0], (byte)rgb[1], (byte)rgb[2]}; + } + + return new XSSFColor(bytes); + } +} diff --git a/src/main/java/com/mitac/cell/doc/HtmlToPdf.java b/src/main/java/com/mitac/cell/doc/HtmlToPdf.java new file mode 100644 index 0000000..f72ed4f --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/HtmlToPdf.java @@ -0,0 +1,39 @@ +package com.mitac.cell.doc; + +import com.lowagie.text.DocumentException; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import org.xhtmlrenderer.pdf.ITextRenderer; + +public class HtmlToPdf { + public static void toPdf(String sourceUrl, String outputFilePath) { + try { + toPdf(sourceUrl, (OutputStream)(new FileOutputStream(outputFilePath))); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + } + + public static void toPdf(String sourceUrl, OutputStream output) { + try { + ITextRenderer renderer = new ITextRenderer(); + renderer.setDocument(sourceUrl); + renderer.layout(); + renderer.createPDF(output); + output.close(); + } catch (FileNotFoundException e2) { + e2.printStackTrace(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (DocumentException e) { + e.printStackTrace(); + } + + } +} diff --git a/src/main/java/com/mitac/cell/doc/McHtmlDoc.java b/src/main/java/com/mitac/cell/doc/McHtmlDoc.java new file mode 100644 index 0000000..6245752 --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/McHtmlDoc.java @@ -0,0 +1,79 @@ +package com.mitac.cell.doc; + +import com.google.common.base.Strings; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; +import org.jsoup.select.Elements; + +public class McHtmlDoc { + public static final String SCHEME_HTTP = "http"; + public static final String SCHEME_HTTPS = "https"; + public static final String TAG_DIV = "div"; + public static final String TAG_META = "meta"; + public static final String TAG_H1 = "h1"; + public static final String TAG_SPAN = "span"; + public static final String TAG_IMG = "img"; + public static final String TAG_A = "a"; + public static final String ATTR_CLASS = "class"; + public static final String ATTR_HREF = "href"; + public static final String ATTR_TITLE = "title"; + public static final String ATTR_NAME = "name"; + public static final String ATTR_SRC = "src"; + public static final String ATTR_ITEMPROP = "itemprop"; + public static final String ATTR_ALT = "alt"; + public static final String ATTR_IMAGE = "image"; + public static final String ATTR_CONTENT = "content"; + public static final String ATTR_DESCRIPTION = "image"; + protected Document document; + + public McHtmlDoc(String url) { + if (!Strings.isNullOrEmpty(url)) { + this.document = McHtmlUtils.loadHtml(url); + } + + } + + public boolean exists() { + return this.document != null; + } + + public Document getDocument() { + return this.document; + } + + public String html() { + return this.document.html(); + } + + public String getDivText(String findAttrName, String findAttrValue) { + return this.getText("div", findAttrName, findAttrValue); + } + + public String getText(String tag, String findAttrName, String findAttrValue) { + return this.getElements(tag, findAttrName, findAttrValue).text(); + } + + public String getAttr(String tag, String findAttrName, String findAttrValue, String attr) { + return this.getElements(tag, findAttrName, findAttrValue).attr(attr); + } + + public Elements getElements(String tag, String findAttrName, String findAttrValue) { + return this.document.select(this.selectEquals(tag, findAttrName, findAttrValue)); + } + + public String getText(Element element, String tag, String findAttrName, String findAttrValue) { + return element.select(this.selectEquals(tag, findAttrName, findAttrValue)).text(); + } + + public String getAttr(Element element, String tag, String findAttrName, String findAttrValue, String attr) { + return element.select(this.selectEquals(tag, findAttrName, findAttrValue)).attr(attr); + } + + public String selectEquals(String tag, String findAttrName, String findAttrValue) { + return String.format("%s[%s=%s]", tag, findAttrName, findAttrValue); + } + + public String selectContains(String tag, String findAttrName, String findAttrValue) { + return String.format("%s[%s*=%s]", tag, findAttrName, findAttrValue); + } +} diff --git a/src/main/java/com/mitac/cell/doc/McHtmlUtils.java b/src/main/java/com/mitac/cell/doc/McHtmlUtils.java new file mode 100644 index 0000000..a169569 --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/McHtmlUtils.java @@ -0,0 +1,49 @@ +package com.mitac.cell.doc; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.parser.Parser; + +public class McHtmlUtils { + public static Document loadHtml(String urlRef) { + return load(urlRef, Parser.htmlParser()); + } + + public static Document load(String urlRef, Parser parser) { + try { + return Jsoup.connect(urlRef).parser(parser).maxBodySize(0).get(); + } catch (MalformedURLException var3) { + } catch (IOException var4) { + } + + return null; + } + + public static Document load(URL url, Parser parser) { + try { + if (url == null) { + return null; + } + + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + conn.setConnectTimeout(10000); + conn.setReadTimeout(5000); + conn.setInstanceFollowRedirects(true); + conn.connect(); + InputStream input = conn.getInputStream(); + Document doc = Jsoup.parse(input, "UTF-8", "", parser); + input.close(); + conn.disconnect(); + return doc; + } catch (MalformedURLException var5) { + } catch (IOException var6) { + } + + return null; + } +} diff --git a/src/main/java/com/mitac/cell/doc/WordTemplate.java b/src/main/java/com/mitac/cell/doc/WordTemplate.java new file mode 100644 index 0000000..590d1da --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/WordTemplate.java @@ -0,0 +1,224 @@ +package com.mitac.cell.doc; + +import com.mitac.cell.internet.http.McHttpClient; +import com.mitac.cell.utils.McStringUtils; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.servlet.http.HttpServletResponse; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.xwpf.usermodel.IBodyElement; +import org.apache.poi.xwpf.usermodel.PositionInParagraph; +import org.apache.poi.xwpf.usermodel.TextSegment; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.apache.poi.xwpf.usermodel.XWPFTable; +import org.apache.poi.xwpf.usermodel.XWPFTableCell; +import org.apache.poi.xwpf.usermodel.XWPFTableRow; + +public class WordTemplate { + private XWPFDocument document; + private Map model; + + public WordTemplate(String filePath) { + this.open(filePath); + } + + public void open(String filePath) { + this.open(new File(filePath)); + } + + public void open(File file) { + try { + if (file.exists()) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + OPCPackage pkg = OPCPackage.open(file); + pkg.save(bos); + pkg.close(); + this.open((InputStream)(new ByteArrayInputStream(bos.toByteArray()))); + } + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void open(InputStream is) { + try { + if (is != null) { + this.document = new XWPFDocument(OPCPackage.open(is)); + } + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void close() { + try { + if (this.document != null) { + this.document.close(); + } + } catch (IOException var2) { + } + + } + + public Map getModel() { + if (this.model == null) { + this.model = new HashMap(); + } + + return this.model; + } + + public void setModel(Map model) { + this.model = model; + } + + public void setModel(String key, Object value) { + this.getModel().put(key, value); + } + + public void patch() { + for(IBodyElement bodyElement : this.document.getBodyElements()) { + switch (bodyElement.getElementType()) { + case PARAGRAPH: + this.patch((XWPFParagraph)bodyElement); + break; + case TABLE: + this.patch((XWPFTable)bodyElement); + } + } + + } + + public void write(String filePath) { + this.write(new File(filePath)); + } + + public void write(File file) { + try { + this.write((OutputStream)(new FileOutputStream(file))); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + } + + public void write(OutputStream os) { + try { + if (os != null) { + this.patch(); + this.document.write(os); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void write(HttpServletResponse response, String fileName) { + if (!McStringUtils.isNullOrEmpty(fileName)) { + try { + response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + response.setHeader("Content-Disposition", McHttpClient.toContentDisposition(fileName)); + this.write((OutputStream)response.getOutputStream()); + response.flushBuffer(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + } + + private void patch(XWPFParagraph paragraph) { + TextSegment segmentStart = paragraph.searchText("{{", new PositionInParagraph()); + if (segmentStart != null) { + XWPFRun run = (XWPFRun)paragraph.getRuns().get(segmentStart.getBeginRun()); + TextSegment segmentEnd = paragraph.searchText("}}", new PositionInParagraph()); + if (segmentEnd != null) { + TextSegment tempEnd = null; + + do { + tempEnd = paragraph.searchText("}}", segmentEnd.getEndPos()); + if (tempEnd != null) { + segmentEnd = tempEnd; + } + } while(tempEnd != null); + + StringBuilder sb = new StringBuilder(run.getText(0)); + int startIndex = segmentStart.getBeginRun() + 1; + int endIndex = segmentEnd.getEndRun() + 1; + int count = endIndex - startIndex; + + for(int i = startIndex; i < startIndex + count; ++i) { + sb.append(paragraph.getRuns().get(startIndex)); + paragraph.removeRun(startIndex); + } + + run.setText(this.parseText(sb.toString()), 0); + } + } + } + + private void patch(XWPFTable table) { + for(XWPFTableRow row : table.getRows()) { + for(XWPFTableCell cell : row.getTableCells()) { + for(XWPFParagraph p : cell.getParagraphs()) { + this.patch(p); + } + } + } + + } + + public String parseText(String source) { + Pattern pattern = Pattern.compile("\\{\\{(.*?)\\}\\}"); + Matcher matcher = pattern.matcher(source); + StringBuilder sb = new StringBuilder(); + + int startIndex; + for(startIndex = 0; matcher.find(); startIndex = matcher.end()) { + sb.append(source.substring(startIndex, matcher.start())); + String group = matcher.group(1); + int index = group.indexOf(124); + String key = index < 0 ? group : group.substring(0, index); + String format = index < 0 ? null : group.substring(index + 1); + Object value = this.model.get(key); + if (value != null) { + if (format == null) { + sb.append(value); + } else if (value instanceof Date) { + SimpleDateFormat formatter = new SimpleDateFormat(format); + sb.append(formatter.format(value)); + } else { + sb.append(String.format(format, value)); + } + } + } + + if (startIndex < source.length()) { + sb.append(source.substring(startIndex)); + } + + return sb.toString(); + } +} diff --git a/src/main/java/com/mitac/cell/gson/typeAdapter/CipherTypeAdapter.java b/src/main/java/com/mitac/cell/gson/typeAdapter/CipherTypeAdapter.java new file mode 100644 index 0000000..a2e1f18 --- /dev/null +++ b/src/main/java/com/mitac/cell/gson/typeAdapter/CipherTypeAdapter.java @@ -0,0 +1,21 @@ +package com.mitac.cell.gson.typeAdapter; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import java.lang.reflect.Type; +import javax.crypto.Cipher; + +public class CipherTypeAdapter implements JsonSerializer, JsonDeserializer { + public Cipher deserialize(JsonElement json, Type typeOfTarget, JsonDeserializationContext context) throws JsonParseException { + return null; + } + + public JsonElement serialize(Cipher src, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(src.getAlgorithm()); + } +} diff --git a/src/main/java/com/mitac/cell/gson/typeAdapter/CompatibleTimeZoneTypeAdapter.java b/src/main/java/com/mitac/cell/gson/typeAdapter/CompatibleTimeZoneTypeAdapter.java new file mode 100644 index 0000000..1c3a0fd --- /dev/null +++ b/src/main/java/com/mitac/cell/gson/typeAdapter/CompatibleTimeZoneTypeAdapter.java @@ -0,0 +1,22 @@ +package com.mitac.cell.gson.typeAdapter; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import java.lang.reflect.Type; +import java.util.TimeZone; + +public class CompatibleTimeZoneTypeAdapter implements JsonSerializer, JsonDeserializer { + public TimeZone deserialize(JsonElement json, Type typeOfTarget, JsonDeserializationContext context) throws JsonParseException { + String timeZone = json.getAsString(); + return TimeZone.getTimeZone(timeZone); + } + + public JsonElement serialize(TimeZone timeZone, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(timeZone.getID()); + } +} diff --git a/src/main/java/com/mitac/cell/internet/app/McPlayMarket.java b/src/main/java/com/mitac/cell/internet/app/McPlayMarket.java new file mode 100644 index 0000000..bddbb8b --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/app/McPlayMarket.java @@ -0,0 +1,80 @@ +package com.mitac.cell.internet.app; + +import com.google.common.base.Strings; +import com.mitac.cell.doc.McHtmlDoc; +import java.util.ArrayList; +import java.util.List; +import org.jsoup.select.Elements; + +public class McPlayMarket { + public static final String BASE_URL = "https://play.google.com"; + private static final String URL_PLAY_STORE = "https://play.google.com/store"; + private static final String URL_APP_URL = "https://play.google.com/store/apps/details?id=%s&hl=%s"; + private static final String URL_APP_SEARCH = "https://play.google.com/store/search?q=%s&hl=%s&c=apps"; + private static final String LOCALE_DEFAULT = "en-GB"; + + public static PlayApp getApkInfo(String packageName) { + return getApkInfo(packageName, "en-GB"); + } + + public static PlayApp getApkInfo(String packageName, String locale) { + if (Strings.isNullOrEmpty(packageName)) { + return null; + } else { + McHtmlDoc doc = new McHtmlDoc(String.format("https://play.google.com/store/apps/details?id=%s&hl=%s", packageName, locale)); + if (!doc.exists()) { + return null; + } else { + PlayApp app = new PlayApp(); + app.setAppId(packageName); + String title = doc.getText("h1", "itemprop", "name"); + app.setTitle(title); + String developer = doc.getText("div", "class", "Vbfug auoIOc"); + app.setDeveloper(developer); + String iconSrc = doc.getAttr("img", "itemprop", "image", "src"); + app.setIcon(iconSrc); + String summary = doc.getAttr("meta", "itemprop", "image", "content"); + app.setSummary(summary); + String score = doc.getText("div", "itemprop", "starRating"); + app.setScore(score); + return app; + } + } + } + + public static List search(String keyword) { + return search(keyword, "en-GB"); + } + + public static List search(String keyword, String locale) { + if (Strings.isNullOrEmpty(keyword)) { + return null; + } else { + McHtmlDoc doc = new McHtmlDoc(String.format("https://play.google.com/store/search?q=%s&hl=%s&c=apps", keyword, locale)); + if (!doc.exists()) { + return null; + } else { + List apps = new ArrayList(); + Elements elements = doc.getElements("div", "class", "VfPpkd-aGsRMb"); + if (elements != null && !elements.isEmpty()) { + elements.forEach((element) -> { + String packageSrc = doc.getAttr(element, "a", "class", "Si6A0c Gy4nib", "href"); + PlayApp app = new PlayApp(); + app.setAppId(packageSrc); + String iconSrc = doc.getAttr(element, "img", "alt", "Thumbnail image", "src"); + app.setIcon(iconSrc); + String title = doc.getText(element, "span", "class", "DdYX5"); + app.setTitle(title); + String developer = doc.getText(element, "span", "class", "wMUdtb"); + app.setDeveloper(developer); + String score = doc.getText(element, "span", "class", "w2kbF"); + app.setScore(score); + apps.add(app); + }); + } + + return apps; + } + } + } +} diff --git a/src/main/java/com/mitac/cell/internet/app/PlayApp.java b/src/main/java/com/mitac/cell/internet/app/PlayApp.java new file mode 100644 index 0000000..ee52558 --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/app/PlayApp.java @@ -0,0 +1,73 @@ +package com.mitac.cell.internet.app; + +import com.google.common.base.Strings; + +public class PlayApp { + private String appId; + private String title; + private String summary; + private String developer; + private String icon; + private Float score; + + public String getAppId() { + return this.appId; + } + + public void setAppId(String appId) { + int idIndex = appId.indexOf("id="); + this.appId = idIndex >= 0 ? appId.substring(idIndex + 3) : appId; + } + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getSummary() { + return this.summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getDeveloper() { + return this.developer; + } + + public void setDeveloper(String developer) { + this.developer = developer; + } + + public String getIcon() { + return this.icon; + } + + public void setIcon(String icon) { + int indexSlash = icon.lastIndexOf("/"); + int endsIndex = icon.lastIndexOf("="); + this.icon = indexSlash >= 0 ? icon.substring(indexSlash + 1, endsIndex > 0 ? endsIndex : icon.length()) : icon; + } + + public Float getScore() { + return this.score; + } + + public void setScore(String score) { + try { + if (!Strings.isNullOrEmpty(score)) { + this.setScore(Float.parseFloat(score)); + } + } catch (Exception var3) { + } + + } + + public void setScore(Float score) { + this.score = score; + } +} diff --git a/src/main/java/com/mitac/cell/internet/html/McHtmlTemplateEngine.java b/src/main/java/com/mitac/cell/internet/html/McHtmlTemplateEngine.java new file mode 100644 index 0000000..2a1e65e --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/html/McHtmlTemplateEngine.java @@ -0,0 +1,52 @@ +package com.mitac.cell.internet.html; + +import java.util.Locale; +import java.util.Map; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.StringTemplateResolver; + +public class McHtmlTemplateEngine extends TemplateEngine { + private final Context context; + private StringTemplateResolver templateResolver; + + public McHtmlTemplateEngine() { + this.context = new Context(); + this.init(); + } + + public McHtmlTemplateEngine(String templateMode, Locale locale) { + this(); + this.setLocale(locale); + this.setTemplateMode(templateMode); + } + + public void setLocale(Locale locale) { + this.context.setLocale(locale); + } + + public void setVariable(String name, Object value) { + this.context.setVariable(name, value); + } + + public void setVariables(Map attrs) { + this.context.setVariables(attrs); + } + + public void setTemplateMode(String templateMode) { + this.templateResolver.setTemplateMode(templateMode); + } + + public String process(String htmlContent) { + String template = null; + this.process(htmlContent, this.context); + return template; + } + + private void init() { + this.templateResolver = new StringTemplateResolver(); + this.templateResolver.setTemplateMode(TemplateMode.HTML); + this.setTemplateResolver(this.templateResolver); + } +} diff --git a/src/main/java/com/mitac/cell/internet/http/McHttpClient.java b/src/main/java/com/mitac/cell/internet/http/McHttpClient.java new file mode 100644 index 0000000..4ec7e1b --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/http/McHttpClient.java @@ -0,0 +1,172 @@ +package com.mitac.cell.internet.http; + +import com.google.common.base.Strings; +import com.google.common.net.UrlEscapers; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import org.apache.commons.io.FilenameUtils; +import org.apache.tika.mime.MimeType; +import org.apache.tika.mime.MimeTypes; +import org.springframework.http.ContentDisposition; + +public class McHttpClient { + public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + public static final String HEADER_USER_AGENT = "User-Agent"; + public static final String HEADER_ENCRPYT_STRING = "encryptString"; + public static final String CONTENT_TYPE_HTML = "text/html; utf-8"; + public static final String CONTENT_TYPE_OCTET_STREAM = "application/octet-stream"; + + public static HttpURLConnection open(String link) { + try { + return Strings.isNullOrEmpty(link) ? null : open(new URL(link)); + } catch (Exception var2) { + return null; + } + } + + public static HttpURLConnection open(URL url) { + try { + HttpURLConnection conn = (HttpURLConnection)url.openConnection(); + conn.setConnectTimeout(60000); + conn.setReadTimeout(180000); + conn.setRequestProperty("User-Agent", "MiDM Host"); + conn.setInstanceFollowRedirects(true); + HttpURLConnection.setFollowRedirects(true); + conn.connect(); + if (isRedirected(conn)) { + conn = getRedirectedConnection(conn); + } + + return conn; + } catch (IOException var2) { + return null; + } + } + + public static boolean isRedirected(HttpURLConnection conn) { + if (conn == null) { + return false; + } else { + try { + int status = conn.getResponseCode(); + return status != 200 && (status == 302 || status == 301 || status == 303); + } catch (IOException var2) { + return false; + } + } + } + + public static HttpURLConnection getRedirectedConnection(HttpURLConnection conn) { + String newUrl = conn.getHeaderField("Location"); + + try { + return (HttpURLConnection)(new URL(newUrl)).openConnection(); + } catch (Exception var3) { + return null; + } + } + + public static InputStream getInputStream(String urlRef) { + try { + return getInputStream(new URL(urlRef)); + } catch (MalformedURLException var2) { + return null; + } + } + + public static InputStream getInputStream(URL url) { + try { + URLConnection connection = url.openConnection(); + return connection.getInputStream(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } + + public static String getFileName(HttpURLConnection conn) { + if (conn != null) { + String fileName = null; + String contentDisposition = conn.getHeaderField("Content-Disposition"); + if (!Strings.isNullOrEmpty(contentDisposition)) { + fileName = getFileNameFromContentDisposition(contentDisposition); + } + + if (Strings.isNullOrEmpty(fileName)) { + String ext = null; + + try { + String contentType = conn.getContentType(); + if (!Strings.isNullOrEmpty(contentType)) { + MimeType type = MimeTypes.getDefaultMimeTypes().getRegisteredMimeType(contentType); + if (type != null) { + ext = type.getExtension(); + } + } + + String path = conn.getURL().getPath(); + path = URLDecoder.decode(path, StandardCharsets.UTF_8.name()); + if (!Strings.isNullOrEmpty(ext) && path.contains(ext)) { + path = path.substring(0, path.indexOf(ext)); + } + + fileName = FilenameUtils.getName(path); + } catch (Exception var6) { + fileName = ""; + } + + if (!fileName.contains(".")) { + fileName = fileName + ext; + } + + if (!Strings.isNullOrEmpty(fileName)) { + return fileName; + } + } + } + + return UUID.randomUUID().toString(); + } + + public static String getFileNameFromContentDisposition(String headerString) { + return ContentDisposition.parse(headerString).getFilename(); + } + + public static String toContentDisposition(String fileName) { + return String.format("attachment; filename=\"%s\"", UrlEscapers.urlFragmentEscaper().escape(fileName)); + } + + public static Cookie findCookie(HttpServletRequest request, String name) { + Cookie foundCookie = null; + + for(Cookie cookie : request.getCookies()) { + if (name.equals(cookie.getName())) { + foundCookie = cookie; + break; + } + } + + return foundCookie; + } + + public static String getCookieValue(String cookie, String key) { + Pattern PATTERN_JSESSIONID = Pattern.compile(String.format("\\b%s=([^;]+)", key)); + Matcher m = PATTERN_JSESSIONID.matcher(cookie); + return m.find() ? m.group(1) : null; + } +} diff --git a/src/main/java/com/mitac/cell/internet/http/McRequest.java b/src/main/java/com/mitac/cell/internet/http/McRequest.java new file mode 100644 index 0000000..8274653 --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/http/McRequest.java @@ -0,0 +1,45 @@ +package com.mitac.cell.internet.http; + +import com.google.common.base.Joiner; +import com.google.common.base.Strings; +import com.mitac.cell.utils.McStringUtils; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import javax.servlet.http.HttpServletRequest; + +public class McRequest { + public static String getBaseUrl(HttpServletRequest request) { + return getBaseUrl(request, (String)null); + } + + public static String getBaseUrl(HttpServletRequest request, String path) { + try { + URL url = new URL(request.getRequestURL().toString()); + String host = url.getHost(); + String scheme = url.getProtocol(); + int port = url.getPort(); + String userInfo = url.getUserInfo(); + String contextPath = request.getContextPath(); + if (!Strings.isNullOrEmpty(path)) { + path = McStringUtils.trim(path.trim(), '/'); + } + + if (Strings.isNullOrEmpty(path)) { + path = contextPath; + } else { + path = Joiner.on('/').join(contextPath, path, new Object[0]).toString(); + } + + URI uri = new URI(scheme, userInfo, host, port, path, (String)null, (String)null); + return uri.toString(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + + return null; + } +} diff --git a/src/main/java/com/mitac/cell/internet/http/McResponse.java b/src/main/java/com/mitac/cell/internet/http/McResponse.java new file mode 100644 index 0000000..609a0fc --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/http/McResponse.java @@ -0,0 +1,74 @@ +package com.mitac.cell.internet.http; + +import com.google.common.base.Strings; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.InputStreamResource; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +public class McResponse { + public static ResponseEntity getServletResource(HttpServletRequest request, MediaType mediaType, String resourcePath) { + ClassPathResource resource = new ClassPathResource(resourcePath); + + try { + InputStream is = resource.getInputStream(); + return getResponseFromStream(request, mediaType, resource.getFilename(), is); + } catch (IOException var5) { + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + } + + public static ResponseEntity getFile(HttpServletRequest request, MediaType mediaType, String path) { + try { + File file = new File(path); + return file.exists() && file.isFile() ? getResponseFromStream(request, mediaType, file.getName(), new FileInputStream(file)) : new ResponseEntity(HttpStatus.NO_CONTENT); + } catch (IOException e) { + e.printStackTrace(); + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + } + + public static ResponseEntity getResponseFromStream(HttpServletRequest request, MediaType mediaType, String fileName, InputStream is) { + try { + ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); + builder.contentLength((long)is.available()); + builder.contentType(mediaType); + builder.header("Content-Disposition", new String[]{McHttpClient.toContentDisposition(fileName)}); + return builder.body(new InputStreamResource(is)); + } catch (IOException e) { + e.printStackTrace(); + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + } + + public static void sendError(HttpServletResponse response, int statusCode, String message) { + try { + response.sendError(statusCode, message); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void setCookie(HttpServletResponse response, String name, String value) { + setCookie(response, "/", name, value); + } + + public static void setCookie(HttpServletResponse response, String path, String name, String value) { + Cookie cookie = new Cookie(name, Strings.isNullOrEmpty(value) ? null : value); + cookie.setPath(path); + if (Strings.isNullOrEmpty(value)) { + cookie.setMaxAge(0); + } + + response.addCookie(cookie); + } +} diff --git a/src/main/java/com/mitac/cell/internet/http/McResponseEntity.java b/src/main/java/com/mitac/cell/internet/http/McResponseEntity.java new file mode 100644 index 0000000..f1c0507 --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/http/McResponseEntity.java @@ -0,0 +1,23 @@ +package com.mitac.cell.internet.http; + +import java.io.InputStream; +import javax.servlet.http.HttpServletRequest; +import org.springframework.core.io.InputStreamResource; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +public class McResponseEntity { + public static ResponseEntity get(HttpServletRequest request, MediaType mediaType, byte[] bytes) { + ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); + builder.contentLength((long)bytes.length); + builder.contentType(mediaType); + return builder.body(bytes); + } + + public static ResponseEntity get(MediaType mediaType, InputStream is, int contentLength) { + ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); + builder.contentLength((long)contentLength); + builder.contentType(mediaType); + return builder.body(new InputStreamResource(is)); + } +} diff --git a/src/main/java/com/mitac/cell/internet/http/UserAgent.java b/src/main/java/com/mitac/cell/internet/http/UserAgent.java new file mode 100644 index 0000000..d541dd2 --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/http/UserAgent.java @@ -0,0 +1,64 @@ +package com.mitac.cell.internet.http; + +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; +import org.yaml.snakeyaml.LoaderOptions; +import ua_parser.Client; +import ua_parser.Device; +import ua_parser.OS; +import ua_parser.Parser; + +public class UserAgent { + private static final Set browsers = (Set)Arrays.stream(new String[]{"chrome", "firefox", "edge", "safari", "vivaldi", "opera"}).collect(Collectors.toSet()); + private static final Parser uaParser = new Parser(new LoaderOptions()); + private Client client; + + public UserAgent(String source) { + if (source.startsWith("MiDM")) { + OS os = uaParser.parseOS(source); + Device device = uaParser.parseDevice(source); + String[] clientVersion = source.substring(source.lastIndexOf("/") + 1).split("\\."); + this.client = new Client(new ua_parser.UserAgent("MiDM", clientVersion[0], clientVersion[1], clientVersion[2]), os, device); + } else { + this.client = uaParser.parse(source); + } + + } + + public OS os() { + return this.client.os; + } + + public String osFamily() { + return this.os().family; + } + + public Device device() { + return this.client.device; + } + + public String deviceFamily() { + return this.device().family; + } + + public Client client() { + return this.client; + } + + public ua_parser.UserAgent agent() { + return this.client.userAgent; + } + + public String agentFamily() { + return this.agent().family; + } + + public boolean isBrowser() { + return this.agentFamily() != null && browsers.contains(this.agent().family.toLowerCase()); + } + + public boolean isDevice() { + return this.agentFamily() != null && this.agent().family.equals("okhttp") || this.agent().family.equals("MiDM"); + } +} diff --git a/src/main/java/com/mitac/cell/internet/mail/McMailSender.java b/src/main/java/com/mitac/cell/internet/mail/McMailSender.java new file mode 100644 index 0000000..3445996 --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/mail/McMailSender.java @@ -0,0 +1,372 @@ +package com.mitac.cell.internet.mail; + +import com.mitac.cell.io.McFile; +import java.io.File; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.Collection; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import javax.mail.Address; +import javax.mail.MessagingException; +import javax.mail.Message.RecipientType; +import javax.mail.internet.InternetAddress; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.InputStreamResource; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.mail.javamail.MimeMessageHelper; + +public class McMailSender { + private MimeMessageHelper mailMessage; + private JavaMailSenderImpl mailSender; + + public McMailSender(JavaMailSenderImpl mailSender, String senderEmail, String senderName) { + this.mailSender = mailSender; + + try { + this.mailMessage = new MimeMessageHelper(mailSender.createMimeMessage(), true, "UTF-8"); + } catch (MessagingException e) { + e.printStackTrace(); + } + + this.setSender(senderEmail, senderName); + } + + public boolean setSender(String email) { + return this.setSender(email, (String)null); + } + + public boolean setSender(String email, String name) { + try { + this.mailMessage.setFrom(email, name); + return true; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (MessagingException e) { + e.printStackTrace(); + } + + return false; + } + + public boolean addTo(String email) { + return this.addTo(email, (String)null); + } + + public boolean addTo(String email, String name) { + try { + this.mailMessage.addTo(email, name); + return true; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (MessagingException e) { + e.printStackTrace(); + } + + return false; + } + + public boolean addTo(InternetAddress address) { + try { + if (address != null) { + this.mailMessage.addTo(address); + } + + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addTo(Collection addresses) { + if (addresses != null && !addresses.isEmpty()) { + addresses.forEach((address) -> this.addTo(address)); + } + + return true; + } + + public boolean setTo(Collection addresses) { + if (addresses != null && !addresses.isEmpty()) { + try { + this.mailMessage.setTo((InternetAddress[])addresses.toArray(new InternetAddress[addresses.size()])); + return true; + } catch (Exception e) { + e.printStackTrace(); + } + } + + return false; + } + + public boolean addCc(String email) { + return this.addCc(email, (String)null); + } + + public boolean addCc(String email, String name) { + try { + this.mailMessage.addCc(email, name); + return true; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (MessagingException e) { + e.printStackTrace(); + } + + return false; + } + + public boolean addCc(InternetAddress address) { + try { + if (address != null) { + this.mailMessage.addCc(address); + } + + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addCc(Collection addresses) { + if (addresses != null && !addresses.isEmpty()) { + addresses.forEach((address) -> this.addCc(address)); + } + + return true; + } + + public boolean addBcc(String email) { + return this.addBcc(email, (String)null); + } + + public boolean addBcc(String email, String name) { + try { + this.mailMessage.addBcc(email, name); + return true; + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (MessagingException e) { + e.printStackTrace(); + } + + return false; + } + + public boolean addBcc(InternetAddress address) { + try { + if (address != null) { + this.mailMessage.addBcc(address); + } + + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addBcc(Collection addresses) { + if (addresses != null && !addresses.isEmpty()) { + addresses.forEach((address) -> this.addBcc(address)); + } + + return true; + } + + public Address[] getAllRecipients() { + try { + return this.mailMessage != null ? this.mailMessage.getMimeMessage().getAllRecipients() : null; + } catch (MessagingException var2) { + return null; + } + } + + public boolean hasRecipients() { + Address[] addresses = this.getAllRecipients(); + return addresses != null && addresses.length > 0; + } + + public void clearTo() { + try { + this.mailMessage.getMimeMessage().setRecipients(RecipientType.TO, (String)null); + } catch (MessagingException e) { + e.printStackTrace(); + } + + } + + public void clearCc() { + try { + this.mailMessage.getMimeMessage().setRecipients(RecipientType.CC, (String)null); + } catch (MessagingException e) { + e.printStackTrace(); + } + + } + + public void clearBcc() { + try { + this.mailMessage.getMimeMessage().setRecipients(RecipientType.BCC, (String)null); + } catch (MessagingException e) { + e.printStackTrace(); + } + + } + + public void clearAllRecipients() { + this.clearTo(); + this.clearCc(); + this.clearBcc(); + } + + public boolean setSubject(String subject) { + try { + this.mailMessage.setSubject(subject); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean setText(String content) { + return this.setContent(content, false); + } + + public boolean setHtml(String content) { + return this.setContent(content, true); + } + + public boolean setContent(String content, boolean isHtml) { + try { + this.mailMessage.setText(content, isHtml); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addAttachment(String filePath) { + McFile file = new McFile(filePath); + return file.exists() ? this.addAttachment((String)file.getName(), (File)file) : false; + } + + public boolean addAttachment(File file, String fileName) { + return file.exists() ? this.addAttachment(fileName, file) : false; + } + + public boolean addAttachment(String... filePaths) { + if (filePaths != null && filePaths.length != 0) { + for(String filePath : filePaths) { + if (!this.addAttachment(filePath)) { + return false; + } + } + + return true; + } else { + return false; + } + } + + public boolean addAttachment(String fileName, File file) { + try { + this.mailMessage.addAttachment(fileName, file); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addAttachment(String fileName, InputStream is) { + try { + this.mailMessage.addAttachment(fileName, new InputStreamResource(is)); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addAttachment(String fileName, byte[] bytes, String contentType) { + try { + this.mailMessage.addAttachment(fileName, new ByteArrayResource(bytes), contentType); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addImage(String filePath) { + McFile file = new McFile(filePath); + return file.exists() ? this.addImage(file.getName(), (File)file) : false; + } + + public boolean addImage(String... filePaths) { + if (filePaths != null && filePaths.length != 0) { + for(String filePath : filePaths) { + if (!this.addImage(filePath)) { + return false; + } + } + + return true; + } else { + return false; + } + } + + public boolean addImage(String fileName, File file) { + try { + this.mailMessage.addInline(fileName, file); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addImage(String fileName, InputStream is) { + try { + this.mailMessage.addInline(fileName, new InputStreamResource(is)); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public boolean addImage(String fileName, byte[] bytes, String contentType) { + try { + this.mailMessage.addInline(fileName, new ByteArrayResource(bytes), contentType); + return true; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + public void send() { + if (this.hasRecipients()) { + Runnable sendMail = new Runnable() { + public void run() { + try { + McMailSender.this.mailSender.send(McMailSender.this.mailMessage.getMimeMessage()); + } catch (Exception ex) { + ex.printStackTrace(); + } + + } + }; + ExecutorService execService = Executors.newFixedThreadPool(1); + execService.execute(sendMail); + execService.shutdown(); + } + } +} diff --git a/src/main/java/com/mitac/cell/internet/websocket/SocketCloseStatus.java b/src/main/java/com/mitac/cell/internet/websocket/SocketCloseStatus.java new file mode 100644 index 0000000..6fbbaba --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/websocket/SocketCloseStatus.java @@ -0,0 +1,48 @@ +package com.mitac.cell.internet.websocket; + +import com.google.common.base.Strings; +import org.springframework.web.socket.CloseStatus; + +public enum SocketCloseStatus { + NORMAL(1000), + GOING_AWAY(1001), + PROTOCOL_ERROR(1002), + NOT_ACCEPTABLE(1003), + NO_STATUS_CODE(1005), + NO_CLOSE_FRAME(1006), + BAD_DATA(1007), + POLICY_VIOLATION(1008), + TOO_BIG_TO_PROCESS(1009), + REQUIRED_EXTENSION(1010), + SERVER_ERROR(1011), + SERVICE_RESTARTED(1012), + SERVICE_OVERLOAD(1013), + TLS_HANDSHAKE_FAILURE(1015), + SESSION_NOT_RELIABLE(4500), + UNKNOWN(-1); + + private int code; + + private SocketCloseStatus(int code) { + this.code = code; + } + + public static SocketCloseStatus get(int code) { + for(SocketCloseStatus status : values()) { + if (status.code == code) { + return status; + } + } + + return UNKNOWN; + } + + public static String reason(CloseStatus status) { + String reason = status.getReason(); + if (Strings.isNullOrEmpty(reason)) { + reason = get(status.getCode()).name(); + } + + return reason; + } +} diff --git a/src/main/java/com/mitac/cell/io/ApkSign.java b/src/main/java/com/mitac/cell/io/ApkSign.java new file mode 100644 index 0000000..af3fcfc --- /dev/null +++ b/src/main/java/com/mitac/cell/io/ApkSign.java @@ -0,0 +1,65 @@ +package com.mitac.cell.io; + +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; + +public class ApkSign { + private String type; + private byte[] certificate; + private byte[] publicKey; + private String algorithm; + private String format; + + public ApkSign(Certificate certificate) { + try { + this.setType(certificate.getType()); + this.setCertificate(certificate.getEncoded()); + this.setPublicKey(certificate.getPublicKey().getEncoded()); + this.setAlgorithm(certificate.getPublicKey().getAlgorithm()); + this.setFormat(certificate.getPublicKey().getFormat()); + } catch (CertificateEncodingException e) { + e.printStackTrace(); + } + + } + + public String getType() { + return this.type; + } + + public void setType(String type) { + this.type = type; + } + + public byte[] getCertificate() { + return this.certificate; + } + + public void setCertificate(byte[] certificate) { + this.certificate = certificate; + } + + public byte[] getPublicKey() { + return this.publicKey; + } + + public void setPublicKey(byte[] publicKey) { + this.publicKey = publicKey; + } + + public String getAlgorithm() { + return this.algorithm; + } + + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } + + public String getFormat() { + return this.format; + } + + public void setFormat(String format) { + this.format = format; + } +} diff --git a/src/main/java/com/mitac/cell/io/McApkFile.java b/src/main/java/com/mitac/cell/io/McApkFile.java new file mode 100644 index 0000000..0b5dbe1 --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McApkFile.java @@ -0,0 +1,248 @@ +package com.mitac.cell.io; + +import com.google.common.base.Strings; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.security.cert.CertificateException; +import java.util.List; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import net.dongliu.apk.parser.ApkFile; +import net.dongliu.apk.parser.bean.AdaptiveIcon; +import net.dongliu.apk.parser.bean.ApkSigner; +import net.dongliu.apk.parser.bean.CertificateMeta; +import net.dongliu.apk.parser.bean.Icon; +import net.dongliu.apk.parser.bean.IconFace; +import net.dongliu.apk.parser.bean.IconPath; +import org.apache.batik.transcoder.TranscoderInput; +import org.apache.batik.transcoder.TranscoderOutput; +import org.apache.batik.transcoder.image.PNGTranscoder; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +public class McApkFile extends ApkFile { + public McApkFile(File apkFile) throws IOException { + super(apkFile); + } + + public McApkFile(String apkFile) throws IOException { + super(new File(apkFile)); + } + + public String getCertMd5() { + try { + List signers = this.getApkSingers(); + if (signers != null && signers.size() > 0) { + return ((CertificateMeta)((ApkSigner)signers.get(0)).getCertificateMetas().get(0)).getCertMd5(); + } + } catch (CertificateException var2) { + } catch (IOException var3) { + } + + return null; + } + + public byte[] iconBytes() { + try { + Icon bigIcon = null; + + for(IconFace icon : this.getAllIcons()) { + if (icon != null) { + if (icon instanceof Icon && icon.isFile()) { + if (bigIcon == null || bigIcon.getDensity() < ((Icon)icon).getDensity()) { + bigIcon = (Icon)icon; + break; + } + } else if (icon instanceof AdaptiveIcon) { + Icon foreground = ((AdaptiveIcon)icon).getForeground(); + if (foreground == null) { + String iconPath = ((IconPath)this.getIconPaths().get(0)).getPath(); + String drawable = this.transBinaryXml(iconPath); + String svg = this.androidVectorDrawableToSvg(drawable); + if (!Strings.isNullOrEmpty(svg)) { + return this.svgToPng(svg); + } + } + } + } + } + + return bigIcon != null ? bigIcon.getData() : null; + } catch (Exception var8) { + return null; + } + } + + public boolean saveIcon(String path) { + byte[] iconBytes = this.iconBytes(); + return iconBytes != null ? (new McFile(path)).write(iconBytes) : false; + } + + public String androidVectorDrawableToSvg(String drawable) { + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document source = builder.parse(new InputSource(new StringReader(drawable))); + Document target = builder.newDocument(); + target.setXmlVersion("1.0"); + Element element = source.getDocumentElement(); + Node svgElement = this.convertToSvg(target, element, (Node)null); + target.appendChild(svgElement); + return this.toXml(target); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + return null; + } catch (SAXException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } + + public Node convertToSvg(Document doc, Node srcNode, Node destNode) { + String nodeName = srcNode.getNodeName(); + Element element = null; + switch (nodeName) { + case "vector": + element = doc.createElement("svg"); + break; + case "path": + element = doc.createElement("path"); + break; + case "group": + element = doc.createElement("g"); + } + + if (element == null) { + return destNode; + } else { + this.setAttribute(srcNode, element); + if (destNode == null) { + destNode = element; + } else { + destNode = destNode.appendChild(element); + } + + NodeList children = srcNode.getChildNodes(); + + for(int i = 0; i < children.getLength(); ++i) { + Node childNode = children.item(i); + this.convertToSvg(doc, childNode, destNode); + } + + return destNode; + } + } + + private void setAttribute(Node srcNode, Element destNode) { + String nodeName = srcNode.getNodeName(); + NamedNodeMap attrs = srcNode.getAttributes(); + if (nodeName.equals("vector")) { + destNode.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + destNode.setAttribute("width", "96"); + destNode.setAttribute("height", "96"); + destNode.setAttribute("viewBox", String.format("%d %d %d %d", 0, 0, 120, 120)); + } else { + for(int i = 0; i < attrs.getLength(); ++i) { + Node attr = attrs.item(i); + String name = attr.getNodeName(); + String value = attr.getNodeValue(); + switch (name) { + case "android:name": + case "android:height": + case "android:width": + case "android:viewportWidth": + case "android:viewportHeight": + case "android:tint": + case "android:tintMode": + case "android:autoMirrored": + case "android:alpha": + case "android:strokeAlpha": + case "android:strokeLineCap": + case "android:strokeLineJoin": + case "android:strokeMiterLimit": + case "android:strokeWidth": + case "android:fillAlpha": + case "android:translateX": + case "android:translateY": + default: + break; + case "android:fillColor": + destNode.setAttribute("fill", this.colorValue(value)); + break; + case "android:pathData": + destNode.setAttribute("d", value); + break; + case "android:strokeColor": + destNode.setAttribute("stroke", this.colorValue(value)); + } + } + } + + } + + private String colorValue(String color) { + if (color.startsWith("#")) { + return color; + } else { + int length = color.length(); + if (length < 6) { + for(int i = 0; i < 6 - length; ++i) { + color = color + "0"; + } + } + + return "#" + color; + } + } + + public String toXml(Document doc) { + try { + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + StringWriter writer = new StringWriter(); + transformer.transform(new DOMSource(doc), new StreamResult(writer)); + return writer.getBuffer().toString().replaceAll("\n|\r", ""); + } catch (TransformerConfigurationException e) { + e.printStackTrace(); + } catch (TransformerException e) { + e.printStackTrace(); + } + + return null; + } + + public byte[] svgToPng(String svg) { + try { + ByteArrayInputStream input = new ByteArrayInputStream(svg.getBytes()); + TranscoderInput transcoderInput = new TranscoderInput(input); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + TranscoderOutput transcoderOutput = new TranscoderOutput(output); + PNGTranscoder pngTranscoder = new PNGTranscoder(); + pngTranscoder.transcode(transcoderInput, transcoderOutput); + byte[] data = output.toByteArray(); + output.close(); + input.close(); + return data; + } catch (Exception var8) { + return null; + } + } +} diff --git a/src/main/java/com/mitac/cell/io/McEncryptedFileDrive.java b/src/main/java/com/mitac/cell/io/McEncryptedFileDrive.java new file mode 100644 index 0000000..0e92c9c --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McEncryptedFileDrive.java @@ -0,0 +1,424 @@ +package com.mitac.cell.io; + +import com.mitac.cell.data.McCompress; +import com.mitac.cell.data.McDecompress; +import com.mitac.cell.security.McCrypto; +import com.mitac.cell.utils.McNumberUtils; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.List; + +public class McEncryptedFileDrive { + private byte[] mKey; + private File mFile; + private boolean mUnclocked; + private boolean mInstantSave; + private McFileTable mFileTable; + private Header mHeader; + + public McEncryptedFileDrive(String path) { + this(new McFile(path)); + } + + public McEncryptedFileDrive(String path, String key) { + this(path, key.getBytes()); + } + + public McEncryptedFileDrive(String path, byte[] key) { + this(path); + this.setKey(key); + } + + public McEncryptedFileDrive(McFile file) { + this.mUnclocked = false; + this.mInstantSave = true; + this.mHeader = new Header(); + this.mFileTable = new McFileTable(); + this.mFile = file; + if (this.mFile.exists()) { + } + + } + + public boolean unlock(String key) { + return this.mUnclocked; + } + + public boolean isSameKey() { + return Arrays.equals(this.mKey, this.mHeader.getKey()); + } + + public void compressed(boolean compressed) { + this.mHeader.compressed(compressed); + } + + public boolean compressed() { + return this.mHeader.compressed(); + } + + public void enableInstantSave(boolean enable) { + this.mInstantSave = enable; + } + + public void setKey(String key) { + this.setKey(key.getBytes()); + } + + public void setKey(byte[] key) { + this.mHeader.setKey(this.mKey = McCrypto.encryptMessageByHmacMd5(key)); + } + + public void setMaxSize(long size) { + } + + public void length() { + } + + public boolean isEncrypted() { + return this.mKey != null; + } + + public void setCurPath(String curPath) { + } + + public McJsonFile getFile(String path) { + return this.mFileTable.getFile(path); + } + + public List getFiles() { + return this.mFileTable.getFiles("/"); + } + + public List getFiles(String path) { + return this.mFileTable.getFiles(path); + } + + public boolean isDirectory(String folderPath) { + return this.mFileTable.getFolder(folderPath) != null; + } + + public boolean isFile(String path) { + return this.mFileTable.getFile(path) != null; + } + + public boolean exists(String path) { + return this.isDirectory(path) || this.isFile(path); + } + + public void addFolder(String folderPath) { + this.mFileTable.addFolder(folderPath); + if (this.mInstantSave) { + this.save(); + } + + } + + public void addFile(String filePath, byte[] data) { + this.mFileTable.addFile(filePath, data); + if (this.mInstantSave) { + this.save(); + } + + } + + public void addFile(String sourcePath, String destinationPath) { + File file = new File(sourcePath); + if (file.exists()) { + this.mFileTable.addFile(sourcePath, destinationPath); + if (this.mInstantSave) { + this.save(); + } + + } + } + + public void copyTo(String orgFilePath, String destinationPath) { + this.mFileTable.getFile(orgFilePath).extractTo(destinationPath); + } + + public void move(String orgfilPath, String destinatinFile) { + } + + public void delete(String path) { + this.remove(path); + } + + public void remove(String path) { + if (!this.mFileTable.removeFolder(path)) { + this.mFileTable.removeFile(path); + } + + if (this.mInstantSave) { + this.save(); + } + + } + + public void rename(String path, String newFileName) { + if (this.mInstantSave) { + this.save(); + } + + } + + public void paste(String destinationFolder) { + if (this.mInstantSave) { + this.save(); + } + + } + + public String[] list(String folderName) { + return null; + } + + public boolean load() { + InputStream ios = null; + ByteArrayOutputStream ous = null; + byte[] source = null; + + try { + byte[] buffer = new byte[8096]; + ios = new BufferedInputStream(new FileInputStream(this.mFile)); + this.mHeader.setBytes(ios); + ous = new ByteArrayOutputStream(); + int read = 0; + + while((read = ios.read(buffer)) != -1) { + ous.write(buffer, 0, read); + } + + source = ous.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (ous != null) { + ous.close(); + } + } catch (IOException var20) { + } + + try { + if (ios != null) { + ios.close(); + } + } catch (IOException var19) { + } + + } + + if (this.mHeader.hasKey() && !this.isSameKey()) { + return false; + } else { + if (this.compressed()) { + source = McDecompress.decompress(source); + } + + source = McCrypto.encryptByAES(this.mKey, source, 0); + return this.mFileTable.setBytes(source); + } + } + + public void extractFiles(String destinationPath) { + this.mFileTable.extractFiles(destinationPath); + } + + public void save() { + try { + OutputStream os = new FileOutputStream(this.mFile); + os.write(this.mHeader.getBytes()); + byte[] source = this.getEncryptedData(); + os.write(source); + os.flush(); + os.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private byte[] getEncryptedData() { + int bufferSize = 65536; + byte[] source = this.mFileTable.getBytes(); + int total = source.length; + + for(int remains = source.length; remains > 0; remains -= bufferSize) { + if (remains < bufferSize) { + bufferSize = remains; + } + + byte[] buffer = new byte[bufferSize]; + System.arraycopy(source, total - remains, buffer, 0, bufferSize); + byte[] encrypted = McCrypto.encryptByAES(this.mKey, buffer, 1); + System.arraycopy(encrypted, 0, source, total - remains, bufferSize); + } + + if (this.compressed()) { + return McCompress.compress(source); + } else { + return source; + } + } + + protected final class Header { + private final byte[] FILE_PREFIX; + private final byte FLAG_TRASHCAN_EANABLED; + private final byte FLAG_COMPRESSED; + private final byte FLAG_HAS_KEY; + private final byte[] mVersion; + private boolean mCompressed; + private boolean mTrashcanEnabled; + private boolean mHasKey; + private byte mReservedFlag; + private byte[] mPassword; + + public Header() { + this(true, false, false); + } + + public Header(boolean compressed, boolean encrypted, boolean trashcanEnabled) { + this.FILE_PREFIX = new byte[]{69, 70, 68, 3}; + this.FLAG_TRASHCAN_EANABLED = 1; + this.FLAG_COMPRESSED = 16; + this.FLAG_HAS_KEY = 32; + this.mVersion = new byte[]{0, 3, 1, 0}; + this.mHasKey = false; + this.mReservedFlag = -1; + this.mCompressed = compressed; + this.mTrashcanEnabled = trashcanEnabled; + } + + public final void setVersion(String version) { + String[] data = version.split("\\."); + + for(int i = 0; i < data.length && i < 4; ++i) { + this.mVersion[i] = Byte.parseByte(data[i]); + } + + } + + public final String getVersion() { + return String.format("%d.%d.%d.%d", this.mVersion[0], this.mVersion[1], this.mVersion[2], this.mVersion[3]); + } + + public final void setKey(byte[] key) { + if (key != null) { + this.mPassword = key; + this.mHasKey = true; + } + + } + + public byte[] getKey() { + return this.mPassword; + } + + public final void compressed(boolean compressed) { + this.mCompressed = compressed; + } + + public final boolean compressed() { + return this.mCompressed; + } + + public final boolean hasKey() { + return this.mHasKey; + } + + public final void trashcanEnabled(boolean trashcanEnabled) { + this.mTrashcanEnabled = trashcanEnabled; + } + + public final boolean trashcanEnabled() { + return this.mTrashcanEnabled; + } + + private final byte getFlag() { + byte flag = 0; + if (this.mCompressed) { + flag = (byte)(flag | 16); + } + + if (this.mTrashcanEnabled) { + flag = (byte)(flag | 1); + } + + if (this.mHasKey) { + flag = (byte)(flag | 32); + } + + return flag; + } + + public final boolean setBytes(byte[] headerBytes) { + return this.setBytes((InputStream)(new ByteArrayInputStream(headerBytes))); + } + + public final boolean setBytes(InputStream bis) { + try { + byte[] header = new byte[4]; + bis.read(header, 0, 4); + if (!Arrays.equals(header, this.FILE_PREFIX)) { + return false; + } else { + bis.read(this.mVersion, 0, 4); + byte flag = (byte)bis.read(); + this.mCompressed = (flag & 16) > 0; + this.mTrashcanEnabled = (flag & 1) > 0; + this.mHasKey = (flag & 32) > 0; + this.mReservedFlag = (byte)bis.read(); + if (this.mHasKey) { + byte[] lenData = new byte[4]; + bis.read(lenData, 0, 4); + int len = McNumberUtils.toInt(true, lenData); + this.mPassword = new byte[len]; + bis.read(this.mPassword, 0, len); + } + + return true; + } + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + public final byte[] getBytes() { + byte[] header = null; + + try { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + byteArrayOutputStream.write(this.FILE_PREFIX); + byteArrayOutputStream.write(this.mVersion); + byteArrayOutputStream.write(this.getFlag()); + byteArrayOutputStream.write(this.mReservedFlag); + if (this.mHasKey) { + int len = this.mPassword.length; + byteArrayOutputStream.write(McNumberUtils.toBytes(4, true, len)); + byteArrayOutputStream.write(this.mPassword); + } + + header = byteArrayOutputStream.toByteArray(); + byteArrayOutputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + return header; + } + } +} diff --git a/src/main/java/com/mitac/cell/io/McFile.java b/src/main/java/com/mitac/cell/io/McFile.java new file mode 100644 index 0000000..4560245 --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McFile.java @@ -0,0 +1,308 @@ +package com.mitac.cell.io; + +import com.google.common.hash.HashFunction; +import com.google.common.hash.Hasher; +import com.google.common.hash.Hashing; +import com.google.common.io.BaseEncoding; +import com.google.common.io.Files; +import com.mitac.cell.utils.McStringUtils; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import org.apache.commons.io.FileUtils; +import org.apache.tika.Tika; + +public class McFile extends File { + public static final long KB = 1024L; + public static final long MB = 1048576L; + public static final long GB = 1073741824L; + public static final long TB = 1099511627776L; + public static String CONTENT_TYPE_XLS = "application/vnd.ms-excel"; + public static String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public McFile(String filePath) { + super(filePath); + } + + public McFile(String folderPath, String fileName) { + super(folderPath, fileName); + } + + public McFile(File file) { + this(file.getPath()); + } + + public McFile(File file, String fileName) { + super(file, fileName); + } + + public McFile(McFile file, String fileName) { + super(file, fileName); + } + + public boolean createParentDirs() { + if (this.getParentFile().exists() && this.getParentFile().isDirectory()) { + return true; + } else { + try { + Files.createParentDirs(this); + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + } + + public boolean createDirs() { + if (!this.createParentDirs()) { + return false; + } else if (!this.exists()) { + return this.mkdir(); + } else { + return this.isDirectory(); + } + } + + public McFile getParentFile() { + return new McFile(this.getParent()); + } + + public String toBase64() { + byte[] bytes = this.toBytes(); + return bytes == null ? null : BaseEncoding.base64().encode(bytes); + } + + public byte[] toBytes() { + try { + return this.exists() ? Files.toByteArray(this) : null; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public String getContentType() { + try { + return (new Tika()).detect(this); + } catch (IOException var2) { + return null; + } + } + + public long getCrcChecksum() { + return this.getCrcChecksum((Integer)null); + } + + public long getCrcChecksum(Integer length) { + HashFunction hf = Hashing.crc32(); + + try { + if (length == null) { + return Files.asByteSource(this).hash(hf).padToLong(); + } else { + Hasher hasher = hf.newHasher(); + BufferedInputStream bis = new BufferedInputStream(this.getInputStream()); + byte[] buffer = new byte[8388608]; + int remained = length; + int n = 0; + int maxLength = remained > buffer.length ? buffer.length : remained; + + while((n = bis.read(buffer, 0, maxLength)) > 0) { + hasher.putBytes(buffer, 0, n); + remained -= n; + if (remained < maxLength) { + maxLength = remained; + } + } + + return hasher.hash().padToLong(); + } + } catch (IOException e1) { + e1.printStackTrace(); + return -1L; + } + } + + public byte[] getMd5() { + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + return md.digest(this.toBytes()); + } catch (NoSuchAlgorithmException var2) { + return null; + } + } + + public String getMd5Hex() { + return McStringUtils.toHexString(this.getMd5()); + } + + public String getExtension() { + return Files.getFileExtension(this.getName()); + } + + public String getNameWithoutExtension() { + return Files.getNameWithoutExtension(this.getName()); + } + + public boolean write(byte[] data) { + ByteArrayInputStream bis = new ByteArrayInputStream(data); + return this.write((InputStream)bis); + } + + public boolean write(InputStream is) { + try { + OutputStream os = this.getOutputStream(); + if (os == null) { + return false; + } + + BufferedOutputStream bos = new BufferedOutputStream(os); + byte[] buffer = new byte[8388608]; + int count = 0; + + while((count = is.read(buffer)) != -1) { + bos.write(buffer, 0, count); + } + + bos.flush(); + bos.close(); + is.close(); + return true; + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return false; + } + + public boolean saveAs(String targetFileName, boolean overwrite) { + return this.saveAs(new McFile(targetFileName), overwrite); + } + + public boolean saveAs(McFile target, boolean overwrite) { + if (this.exists() && !target.isDirectory()) { + if (target.exists() && !overwrite) { + return false; + } else { + try { + Files.copy(this, target); + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + } else { + return false; + } + } + + public boolean moveFrom(McFile file) { + if (!file.exists()) { + return false; + } else { + try { + FileUtils.forceMkdirParent(this); + return this.write(file.getInputStream()) ? file.delete() : false; + } catch (IOException var3) { + return false; + } + } + } + + public boolean moveFrom(File file) { + return this.moveFrom(new McFile(file)); + } + + public boolean moveTo(String path) { + return (new McFile(path)).moveFrom(this); + } + + public boolean delete() { + if (!this.exists()) { + return true; + } else if (this.isFile()) { + return super.delete(); + } else { + File[] files = this.listFiles(); + boolean cleared = true; + if (files != null && files.length > 0) { + for(File file : files) { + if (!(new McFile(file.getPath())).delete()) { + cleared = false; + break; + } + } + } + + if (cleared) { + super.delete(); + } + + return true; + } + } + + public boolean deleteParent() { + try { + FileUtils.deleteDirectory(this.getParentFile()); + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + public InputStream getInputStream() { + try { + return new FileInputStream(this); + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public OutputStream getOutputStream() { + try { + return new FileOutputStream(this); + } catch (FileNotFoundException var2) { + return null; + } + } + + public static boolean exists(String path) { + return (new McFile(path)).exists(); + } + + public long length() { + long total = 0L; + if (!this.exists()) { + return -1L; + } else { + if (this.isDirectory()) { + String[] fileList = this.list(); + if (fileList != null) { + for(String fileName : this.list()) { + total += (new McFile(this, fileName)).length(); + } + } + } else { + total += super.length(); + } + + return total; + } + } +} diff --git a/src/main/java/com/mitac/cell/io/McFileTable.java b/src/main/java/com/mitac/cell/io/McFileTable.java new file mode 100644 index 0000000..8cb89d6 --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McFileTable.java @@ -0,0 +1,259 @@ +package com.mitac.cell.io; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.mitac.cell.net.Uri; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McNumberUtils; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class McFileTable { + private static final String KEY_EFD = "EFD"; + private static final String KEY_FILE = "file"; + private JsonObject mFileTable = new JsonObject(); + private JsonObject mRoot = new JsonObject(); + private final ArrayList mFileArray; + + public McFileTable() { + this.mFileTable.add("EFD", this.mRoot); + this.mFileArray = new ArrayList(); + } + + public void addFile(String sourceFilePath, String destinationPath) { + JsonObject targetFolder = this.addFolder((new File(destinationPath)).getParent()); + JsonArray filesArray = this.getFilesArray(targetFolder); + McJsonFile jsonFile = new McJsonFile(sourceFilePath, destinationPath); + filesArray.add(jsonFile.toJsonObject()); + this.mFileArray.add(jsonFile); + } + + public void addFile(String destinationFile, byte[] data) { + JsonObject targetFolder = this.addFolder((new File(destinationFile)).getParent()); + JsonArray filesArray = this.getFilesArray(targetFolder); + McJsonFile jsonFile = new McJsonFile(destinationFile); + jsonFile.setData(data); + filesArray.add(jsonFile.toJsonObject()); + this.mFileArray.add(jsonFile); + } + + public boolean removeFile(String path) { + File file = new File(path); + JsonObject folder = this.getFolder(file.getParent()); + if (folder == null) { + return false; + } else { + JsonArray files = folder.getAsJsonArray("file"); + if (files == null) { + return false; + } else { + JsonArray newFiles = new JsonArray(); + String fileName = file.getName(); + + for(JsonElement jFile : files) { + McJsonFile jsonFile = new McJsonFile(jFile.getAsJsonObject()); + if (!fileName.equals(jsonFile.getName())) { + newFiles.add(jsonFile.toJsonObject()); + } else { + this.mFileArray.remove(jsonFile); + } + } + + folder.add("file", newFiles); + return false; + } + } + } + + private String[] getNames(JsonObject jPath) { + String[] names = new String[jPath.size()]; + int i = 0; + + for(Map.Entry jFile : jPath.entrySet()) { + names[i++] = (String)jFile.getKey(); + } + + return names; + } + + public ArrayList getFiles(String path) { + JsonObject folder = this.getFolder(path); + String[] names = this.getNames(folder); + if (names == null) { + return null; + } else { + ArrayList fileArray = new ArrayList(); + + for(String name : names) { + if (!name.equals("file")) { + fileArray.add(new McFile(name)); + } + } + + JsonArray files = folder.getAsJsonArray("file"); + if (files != null) { + for(JsonElement jFile : files) { + McJsonFile jsonFile = new McJsonFile(jFile.getAsJsonObject()); + fileArray.add(new McFile(jsonFile.getName())); + } + } + + return fileArray; + } + } + + public McJsonFile getFile(String path) { + File file = new File(path); + JsonObject folder = this.getFolder(file.getParent()); + if (folder == null) { + return null; + } else { + JsonArray jFiles = folder.getAsJsonArray("file"); + if (jFiles == null) { + return null; + } else { + String fileName = file.getName(); + + for(JsonElement jFile : jFiles) { + McJsonFile jsonFile = new McJsonFile(jFile.getAsJsonObject()); + if (fileName.equals(jsonFile.getName())) { + return jsonFile; + } + } + + return null; + } + } + } + + public JsonObject getFolder(String folderPath) { + Uri uri = Uri.parse(folderPath); + List paths = uri.getPathSegments(); + return paths.size() > 0 && this.mRoot.has((String)paths.get(0)) ? this.mRoot.getAsJsonObject((String)paths.get(0)) : this.mRoot; + } + + private JsonArray getFilesArray(JsonObject jsonFolder) { + JsonArray fileArray = jsonFolder.getAsJsonArray("file"); + if (fileArray == null) { + fileArray = new JsonArray(); + jsonFolder.add("file", fileArray); + } + + return fileArray; + } + + public JsonObject addFolder(String path) { + if (path != null && !path.isEmpty()) { + Uri uri = Uri.parse(path); + List paths = uri.getPathSegments(); + JsonObject targetFolder = this.mRoot; + + for(String pathSegment : paths) { + JsonObject jFolder = targetFolder.getAsJsonObject(pathSegment); + if (jFolder != null && jFolder.isJsonObject()) { + targetFolder = jFolder; + } else { + jFolder = new JsonObject(); + targetFolder.add(pathSegment, jFolder); + targetFolder = jFolder; + } + } + + return targetFolder; + } else { + return this.mRoot; + } + } + + public boolean removeFolder(String path) { + Uri uri = Uri.parse(path); + List paths = uri.getPathSegments(); + if (this.mRoot.has((String)paths.get(0))) { + this.mRoot.remove((String)paths.get(0)); + return true; + } else { + return false; + } + } + + public void extractFiles(String destinationPath) { + for(int i = 0; i < this.mFileArray.size(); ++i) { + McJsonFile file = (McJsonFile)this.mFileArray.get(i); + file.extract(destinationPath); + } + + } + + public boolean setBytes(byte[] buffer) { + ByteArrayInputStream bos = new ByteArrayInputStream(buffer); + byte[] data = new byte[4]; + bos.read(data, 0, 4); + int len = McNumberUtils.toInt(true, data); + data = new byte[len]; + bos.read(data, 0, len); + this.mFileTable = McJsonUtils.toJson(data).getAsJsonObject(); + this.mRoot = this.mFileTable.getAsJsonObject("EFD"); + int startOffset = len + 4; + this.dispatchFiles(buffer, this.mRoot, startOffset); + return true; + } + + private void dispatchFiles(byte[] buffer, JsonObject fileTable, int startOffset) { + for(Map.Entry entry : fileTable.entrySet()) { + JsonElement jPath = (JsonElement)entry.getValue(); + if (jPath.isJsonObject()) { + this.dispatchFiles(buffer, jPath.getAsJsonObject(), startOffset); + } else if (jPath.isJsonArray()) { + for(JsonElement jChild : jPath.getAsJsonArray()) { + McJsonFile jFile = new McJsonFile(jChild.getAsJsonObject()); + int offset = jFile.getOffset(); + int size = jFile.getSize(); + byte[] data = new byte[size]; + System.arraycopy(buffer, startOffset + offset, data, 0, size); + jFile.setData(data); + this.mFileArray.add(jFile); + } + } + } + + } + + public byte[] getBytes() { + try { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + int offset = 0; + + for(int i = 0; i < this.mFileArray.size(); ++i) { + McJsonFile jsonFile = (McJsonFile)this.mFileArray.get(i); + jsonFile.setOffset(offset); + jsonFile.update(); + offset += jsonFile.getSize(); + } + + byte[] data = this.mFileTable.toString().getBytes(); + byteArrayOutputStream.write(McNumberUtils.toBytes(4, true, data.length)); + byteArrayOutputStream.write(data); + + for(int i = 0; i < this.mFileArray.size(); ++i) { + byteArrayOutputStream.write(((McJsonFile)this.mFileArray.get(i)).getData()); + } + + int n = 16 - byteArrayOutputStream.size() % 16; + + for(int i = 0; i < n; ++i) { + byteArrayOutputStream.write(0); + } + + return byteArrayOutputStream.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/com/mitac/cell/io/McInputStream.java b/src/main/java/com/mitac/cell/io/McInputStream.java new file mode 100644 index 0000000..3f55982 --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McInputStream.java @@ -0,0 +1,22 @@ +package com.mitac.cell.io; + +import com.google.common.io.BaseEncoding; +import com.google.common.io.ByteStreams; +import java.io.IOException; +import java.io.InputStream; + +public class McInputStream { + public static byte[] toBytes(InputStream is) { + try { + return ByteStreams.toByteArray(is); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static String toBase64Encoded(InputStream is) { + byte[] bytes = toBytes(is); + return bytes == null ? null : BaseEncoding.base64().encode(bytes); + } +} diff --git a/src/main/java/com/mitac/cell/io/McJsonFile.java b/src/main/java/com/mitac/cell/io/McJsonFile.java new file mode 100644 index 0000000..aef6284 --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McJsonFile.java @@ -0,0 +1,155 @@ +package com.mitac.cell.io; + +import com.google.common.io.Files; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.mitac.cell.utils.McJsonUtils; +import com.mitac.cell.utils.McStringUtils; +import java.io.File; +import java.io.IOException; +import java.sql.Date; + +public class McJsonFile { + private static final String KEY_NAME = "name"; + private static final String KEY_OFFSET = "offset"; + private static final String KEY_SIZE = "size"; + private static final String KEY_UPDATED = "updated"; + private static final String KEY_PERMISSION = "permission"; + private static final String KEY_DATA = "data"; + private JsonObject jFile; + + public McJsonFile(File sourceFile) { + this.jFile = new JsonObject(); + this.setName(sourceFile.getName()); + this.setData(sourceFile); + } + + public McJsonFile(String filePath) { + this(new File(filePath)); + } + + public McJsonFile(String sourceFile, String destinationFile) { + this.setName(destinationFile); + this.setData(new File(sourceFile)); + } + + public McJsonFile(File sourceFile, String destinationFile) { + this.setName(destinationFile); + this.setData(sourceFile); + } + + public McJsonFile(String destinationFile, byte[] data) { + this.setName(destinationFile); + this.setData(data); + } + + public McJsonFile(JsonObject jsonFile) { + this.jFile = jsonFile; + } + + public void setName(String name) { + this.jFile.addProperty("name", name); + } + + public String getName() { + return this.jFile.getAsJsonPrimitive("name").getAsString(); + } + + public void update() { + this.jFile.addProperty("size", this.getData().length); + } + + public void setData(File file) { + if (file.exists()) { + try { + this.jFile.addProperty("size", file.length()); + this.setData(Files.toByteArray(file)); + this.jFile.addProperty("updated", file.lastModified()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + + public void setData(byte[] data) { + String base64 = McStringUtils.toBase64(data); + if (base64 != null) { + this.jFile.addProperty("data", base64); + this.jFile.addProperty("updated", System.currentTimeMillis()); + } + + } + + public byte[] getData() { + if (this.jFile.has("data")) { + JsonPrimitive jPrimitive = this.jFile.getAsJsonPrimitive("data"); + return McStringUtils.fromBase64(jPrimitive.getAsString()); + } else { + return null; + } + } + + public JsonObject toJsonObject() { + JsonElement jsonElement = McJsonUtils.toJsonElement((Object)this.jFile); + return jsonElement.getAsJsonObject(); + } + + public String toString() { + return this.jFile.toString(); + } + + public void extract(String destinationPath) { + McFile file = new McFile(destinationPath, this.getName()); + file.write(this.getData()); + } + + public void extractTo(String destinationPath) { + McFile file = new McFile(destinationPath); + file.write(this.getData()); + } + + public void setLastUpdated(Date date) { + this.setLastUpdated(date.getTime()); + } + + public void setLastUpdated(long date) { + this.jFile.addProperty("updated", date); + } + + public Date getLastUpdated() { + if (this.jFile.has("updated")) { + long date = this.jFile.getAsJsonPrimitive("updated").getAsLong(); + return new Date(date); + } else { + return null; + } + } + + public int getSize() { + if (this.jFile.has("size")) { + int size = this.jFile.getAsJsonPrimitive("size").getAsInt(); + return size; + } else { + return 0; + } + } + + public int getOffset() { + if (this.jFile.has("offset")) { + int offset = this.jFile.getAsJsonPrimitive("offset").getAsInt(); + return offset; + } else { + return 0; + } + } + + public void setOffset(int value) { + this.jFile.addProperty("offset", value); + } + + public void setPermission(String value) { + this.jFile.addProperty("permission", value); + } +} diff --git a/src/main/java/com/mitac/cell/io/McResource.java b/src/main/java/com/mitac/cell/io/McResource.java new file mode 100644 index 0000000..0f5275e --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McResource.java @@ -0,0 +1,183 @@ +package com.mitac.cell.io; + +import com.google.common.base.Strings; +import com.google.common.io.ByteStreams; +import com.mitac.cell.internet.http.McHttpClient; +import com.mitac.cell.internet.http.McResponse; +import com.mitac.cell.utils.McStringUtils; +import java.awt.image.BufferedImage; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import javax.imageio.ImageIO; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.io.IOUtils; + +public class McResource { + public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, McFile file, String fileName, long lastModified, String range, long checksum) { + Integer to = -1; + Integer from = -1; + if (!Strings.isNullOrEmpty(range)) { + range = range.substring(range.indexOf(61) + 1); + if (range.indexOf(44) >= 0) { + McResponse.sendError(response, 400, "Multiple ranges not supported."); + return; + } + + boolean isRangeOk = true; + if (range.indexOf(45) >= 0) { + String[] tokens = range.split("-"); + if (tokens.length > 0) { + if (Strings.isNullOrEmpty(tokens[0])) { + to = (int)file.length() - 1; + from = to - Integer.valueOf(tokens[1]) + 1; + } else { + from = Integer.valueOf(tokens[0]); + if (tokens.length > 1) { + if (Strings.isNullOrEmpty(tokens[1])) { + to = (int)file.length() - 1; + } else { + to = Integer.valueOf(tokens[1]); + } + } else { + to = (int)file.length() - 1; + } + } + } else { + isRangeOk = false; + } + } + + if (!isRangeOk) { + McResponse.sendError(response, 400, "Range is invalid."); + return; + } + + response.addHeader("Accept-Ranges", "bytes"); + } + + response.addHeader("ETag", String.valueOf(checksum)); + response.setDateHeader("Last-Modified", lastModified); + copyFileToResponse(servletContext, response, file, fileName, from, to); + } + + public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, McFile file, String fileName, int from, int to) { + if (McStringUtils.isNullOrEmpty(fileName)) { + fileName = file.getName(); + } + + if (file.exists()) { + int fileSize = (int)file.length(); + int maxRange = fileSize > 0 ? fileSize - 1 : 0; + response.setContentType(servletContext.getMimeType(fileName)); + if (to < 0 || to > maxRange) { + to = maxRange; + } + + if (from < 0) { + from = 0; + } else if (from > maxRange || from > to) { + try { + response.sendError(416, "Requested Range Not Satisfiable."); + } catch (IOException var9) { + } + + return; + } + + if (from <= 0 && to >= maxRange) { + response.setContentLength(fileSize); + } else { + response.setStatus(206); + response.setHeader("Content-Range", String.format("bytes %d-%d/%d", from, to, fileSize)); + response.setContentLength(to - from + 1); + response.setHeader("position", Long.toString((long)from)); + } + + response.setHeader("Content-Disposition", McHttpClient.toContentDisposition(fileName)); + copyToResponse(servletContext, response, file, from, to); + } else { + try { + response.sendError(404, "File not exists."); + } catch (IOException var10) { + } + } + + } + + public static void copyToResponse(ServletContext servletContext, HttpServletResponse response, InputStream is) { + try { + ByteStreams.copy(is, response.getOutputStream()); + response.flushBuffer(); + is.close(); + } catch (IOException var6) { + try { + response.sendError(404, "Inputstream not work."); + } catch (IOException var5) { + } + } + + } + + public static void copyToResponse(ServletContext servletContext, HttpServletResponse response, File file, int from, int to) { + try { + if (file.exists()) { + RandomAccessFile raFile = new RandomAccessFile(file, "r"); + BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream()); + if (from > 0) { + raFile.seek((long)from); + } + + if (to < 0) { + to = (int)raFile.length() - 1; + } + + int length = 9863168; + byte[] buffer = new byte[length]; + + int read; + for(read = -1; from < to && (read = raFile.read(buffer, 0, length)) > 0; from += read) { + output.write(buffer, 0, read); + } + + raFile.close(); + response.flushBuffer(); + output.close(); + } else { + response.sendError(404, "File not exists."); + } + } catch (Exception var10) { + } + + } + + public static void copyToResponse(HttpServletResponse response, BufferedImage image) { + try { + response.setContentType("image/png"); + ImageIO.write(image, "png", response.getOutputStream()); + response.flushBuffer(); + } catch (IOException var3) { + } + + } + + public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, byte[] data, String fileName) { + response.setContentType(servletContext.getMimeType(fileName)); + response.setHeader("Content-Disposition", McHttpClient.toContentDisposition(fileName)); + + try { + IOUtils.write(data, response.getOutputStream()); + response.flushBuffer(); + } catch (IOException var5) { + } + + } + + public static void setNoCacheControl(HttpServletResponse response) { + response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + response.setHeader("Expires", "0"); + } +} diff --git a/src/main/java/com/mitac/cell/io/McUrl.java b/src/main/java/com/mitac/cell/io/McUrl.java new file mode 100644 index 0000000..da9e8bb --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McUrl.java @@ -0,0 +1,81 @@ +package com.mitac.cell.io; + +import com.google.common.io.BaseEncoding; +import com.google.common.io.Resources; +import com.mitac.cell.net.McNetUtils; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import javax.servlet.http.HttpServletRequest; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.InputStreamResource; +import org.springframework.core.io.InputStreamSource; + +public class McUrl { + public static String getHost(HttpServletRequest request) { + return request == null ? null : getHost(request.getRequestURL().toString()); + } + + public static String getHost(String stringUrl) { + try { + URL url = new URL(stringUrl); + return url == null ? null : McNetUtils.getHost(url.getHost()); + } catch (MalformedURLException var2) { + return null; + } + } + + public static byte[] toBytes(String url) { + try { + return toBytes(new URL(url)); + } catch (MalformedURLException e) { + e.printStackTrace(); + return null; + } + } + + public static byte[] toBytes(URL url) { + try { + return Resources.toByteArray(url); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static String toBase64Encoded(String url) { + byte[] bytes = toBytes(url); + return bytes == null ? null : BaseEncoding.base64().encode(bytes); + } + + public static String toBase64Encoded(URL url) { + byte[] bytes = toBytes(url); + return bytes == null ? null : BaseEncoding.base64().encode(bytes); + } + + public static InputStreamSource toInputStreamSource(String url) { + byte[] bytes = toBytes(url); + return bytes == null ? null : new ByteArrayResource(bytes); + } + + public static InputStream toInputStream(URL url) { + try { + return url.openStream(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static InputStreamResource toInputStreamResource(URL url) { + if (url != null) { + InputStream is = toInputStream(url); + if (is != null) { + return new InputStreamResource(is); + } + } + + return null; + } +} diff --git a/src/main/java/com/mitac/cell/io/McZipFile.java b/src/main/java/com/mitac/cell/io/McZipFile.java new file mode 100644 index 0000000..0ad202e --- /dev/null +++ b/src/main/java/com/mitac/cell/io/McZipFile.java @@ -0,0 +1,247 @@ +package com.mitac.cell.io; + +import com.google.common.base.Strings; +import com.google.common.collect.Sets; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Set; +import net.lingala.zip4j.ZipFile; +import net.lingala.zip4j.exception.ZipException; +import net.lingala.zip4j.model.ZipParameters; +import net.lingala.zip4j.model.enums.CompressionLevel; +import net.lingala.zip4j.model.enums.CompressionMethod; +import net.lingala.zip4j.model.enums.EncryptionMethod; + +public class McZipFile extends McFile { + private static final long serialVersionUID = 1L; + private ZipFile zipFile; + private ZipParameters zipParams; + + public McZipFile(String zipFilePath) { + super(zipFilePath); + this.genZipFile(); + } + + public McZipFile(File zipFile) { + super(zipFile); + this.genZipFile(); + } + + public McZipFile(String folder, String name) { + super(new McFile(folder), name); + this.genZipFile(); + } + + public McZipFile(File file, String name) { + super(file, name); + this.genZipFile(); + } + + public boolean save() { + return this.saveAs(this, true); + } + + public boolean save(boolean overwrite) { + return this.saveAs(this, true); + } + + private void genZipFile() { + this.zipFile = new ZipFile(this.getAbsolutePath()); + } + + public boolean isZipped() { + return this.zipFile.isValidZipFile(); + } + + public boolean compressFolder(String folder, boolean includeFolder) { + McFile dir = new McFile(folder); + if (dir.exists() && !dir.isFile()) { + if (includeFolder) { + return this.compress(dir.getPath()); + } else { + File[] files = dir.listFiles(); + String[] filePaths = new String[files.length]; + + for(int i = 0; i < files.length; ++i) { + filePaths[i] = files[i].getPath(); + } + + return this.compress(filePaths); + } + } else { + return false; + } + } + + public boolean compress(File... filesToBeCompressed) { + String[] paths = new String[filesToBeCompressed.length]; + + for(int i = 0; i < filesToBeCompressed.length; ++i) { + paths[i] = filesToBeCompressed[i].getPath(); + } + + return this.compress(paths); + } + + public boolean compress(String... filePathToBeCompressed) { + return this.compress((String)null, true, false, filePathToBeCompressed); + } + + public boolean compress(String fileName, InputStream input) { + return this.compress((String)null, true, false, fileName, input); + } + + public boolean compress(String password, boolean overwriteIfExists, boolean deleteOnSucceed, String... pathsToBeCompressed) { + if (!this.exists() || !this.isDirectory() && overwriteIfExists && pathsToBeCompressed != null) { + if (!this.getParentFile().exists()) { + this.createParentDirs(); + } + + try { + Set paths = Sets.newHashSet(pathsToBeCompressed); + boolean hasPassword = Strings.isNullOrEmpty(password); + if (hasPassword) { + this.zipFile.setPassword(password.toCharArray()); + } + + this.zipParams = this.getZipParams(hasPassword); + + for(String path : paths) { + McFile file = new McFile(path); + if (file.exists()) { + if (file.isFile()) { + this.zipFile.addFile(file, this.zipParams); + } else { + this.zipFile.addFolder(file, this.zipParams); + } + + if (deleteOnSucceed) { + file.delete(); + } + } + } + + return true; + } catch (ZipException e) { + e.printStackTrace(); + return false; + } + } else { + return false; + } + } + + public boolean compress(String password, boolean overwriteIfExists, boolean deleteOnSucceed, String fileName, InputStream input) { + if (input != null && !Strings.isNullOrEmpty(fileName)) { + try { + boolean hasPassword = Strings.isNullOrEmpty(password); + if (hasPassword) { + this.zipFile.setPassword(password.toCharArray()); + } + + this.zipParams = this.getZipParams(hasPassword); + this.zipParams.setFileNameInZip(fileName); + this.zipFile.addStream(input, this.zipParams); + input.close(); + return true; + } catch (ZipException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return false; + } else { + return false; + } + } + + public boolean compressAs(File file, String name) { + if (file != null && file.exists()) { + try { + this.zipParams = this.getZipParams(false); + this.zipParams.setFileNameInZip(Strings.isNullOrEmpty(name) ? file.getName() : name); + this.zipFile.addFolder(file, this.zipParams); + return true; + } catch (ZipException e) { + e.printStackTrace(); + return false; + } + } else { + return false; + } + } + + public boolean extract(String extractTo) { + return this.extract(extractTo, (String)null, false, false); + } + + public boolean extract(String extractTo, String password) { + return this.extract(extractTo, password, false, false); + } + + public boolean extract(String extractTo, String password, boolean deleteOnExists, boolean deleteOnSuccess) { + if (this.isDirectory()) { + return false; + } else { + try { + ZipFile zipFile = new ZipFile(this); + if (zipFile.isEncrypted()) { + if (Strings.isNullOrEmpty(password)) { + zipFile.close(); + return false; + } + + zipFile.setPassword(password.toCharArray()); + } + + McFile destFile = new McFile(extractTo); + destFile.createParentDirs(); + if (destFile.exists() && deleteOnExists) { + destFile.delete(); + } + + zipFile.extractAll(extractTo); + if (deleteOnSuccess) { + this.delete(); + } + + zipFile.close(); + } catch (IOException var7) { + } + + return false; + } + } + + public ZipParameters getZipParams(int deflateLevel) { + return this.getZipParams(this.getLevel(deflateLevel), false); + } + + public ZipParameters getZipParams(boolean hasPassword) { + return this.getZipParams(CompressionLevel.NORMAL, hasPassword); + } + + public ZipParameters getZipParams(CompressionLevel deflateLevel, boolean hasPassword) { + ZipParameters zParams = new ZipParameters(); + zParams.setCompressionMethod(CompressionMethod.DEFLATE); + zParams.setCompressionLevel(deflateLevel); + if (hasPassword) { + zParams.setEncryptFiles(true); + zParams.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); + } + + return zParams; + } + + private CompressionLevel getLevel(int level) { + for(CompressionLevel compressionLevel : CompressionLevel.values()) { + if (compressionLevel.getLevel() == level) { + return compressionLevel; + } + } + + return CompressionLevel.NORMAL; + } +} diff --git a/src/main/java/com/mitac/cell/io/Vector2Svg.java b/src/main/java/com/mitac/cell/io/Vector2Svg.java new file mode 100644 index 0000000..a574298 --- /dev/null +++ b/src/main/java/com/mitac/cell/io/Vector2Svg.java @@ -0,0 +1,226 @@ +package com.mitac.cell.io; + +import com.mitac.cell.utils.McStringUtils; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +public class Vector2Svg { + private final InputStream source; + + public Vector2Svg(String source) throws FileNotFoundException { + this(new File(source)); + } + + public Vector2Svg(File source) throws FileNotFoundException { + this((InputStream)(new FileInputStream(source))); + } + + public Vector2Svg(byte[] data) { + this((InputStream)(new ByteArrayInputStream(data))); + } + + public Vector2Svg(InputStream source) { + this.source = source; + } + + public byte[] toSvgBytes() { + try { + AndroidVectorDrawable drawable = this.getDrawable(); + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + Element svg = doc.createElement("svg"); + svg.setAttribute("viewBox", String.format("0 0 %.1f %.1f", drawable.width, drawable.height)); + + for(Group group : drawable.groups) { + Element g = doc.createElement("g"); + + for(VectorPath path : group.paths) { + Element child = doc.createElement("path"); + if (path.fillColor != null) { + child.setAttribute("fill", path.fillColor); + } + + child.setAttribute("d", path.pathData); + g.appendChild(child); + } + + svg.appendChild(g); + } + + for(VectorPath path : drawable.paths) { + Element child = doc.createElement("path"); + if (path.fillColor != null) { + child.setAttribute("fill", path.fillColor); + } + + child.setAttribute("d", path.pathData); + svg.appendChild(child); + } + + doc.appendChild(svg); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(doc); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + StreamResult result = new StreamResult(output); + transformer.setOutputProperty("omit-xml-declaration", "yes"); + transformer.setOutputProperty("indent", "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + transformer.transform(source, result); + return output.toByteArray(); + } catch (Exception var10) { + return null; + } + } + + private AndroidVectorDrawable getDrawable() throws ParserConfigurationException, IOException, SAXException { + Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(this.source); + xml.getDocumentElement().normalize(); + Node vector = xml.getElementsByTagName("vector").item(0); + NamedNodeMap attributes = vector.getAttributes(); + NodeList children = vector.getChildNodes(); + double width = (double)0.0F; + double height = (double)0.0F; + + for(int i = 0; i < attributes.getLength(); ++i) { + if (attributes.item(i).getNodeName().equals("android:viewportHeight")) { + height = this.getDouble(attributes.item(i).getNodeValue()); + } else if (attributes.item(i).getNodeName().equals("android:viewportWidth")) { + width = this.getDouble(attributes.item(i).getNodeValue()); + } + } + + List paths = new ArrayList(); + List groups = new ArrayList(); + + for(int i = 0; i < children.getLength(); ++i) { + Node item = children.item(i); + if (!item.getNodeName().equals("group")) { + VectorPath path = this.getVectorPathFromNode(item); + if (path != null) { + paths.add(path); + } + } else { + List groupPaths = new ArrayList(); + + for(int j = 0; j < item.getChildNodes().getLength(); ++j) { + VectorPath path = this.getVectorPathFromNode(item.getChildNodes().item(j)); + if (path != null) { + groupPaths.add(path); + } + } + + if (!groupPaths.isEmpty()) { + groups.add(new Group(groupPaths)); + } + } + } + + return new AndroidVectorDrawable(paths, groups, width, height); + } + + private Double getDouble(String nodeValue) { + if (nodeValue.startsWith("{")) { + String[] token = nodeValue.split(":"); + Double d1 = Double.parseDouble(token[0].substring(1)); + Double d2 = Double.parseDouble(token[1].substring(0, token[1].length() - 1)) / (double)1024.0F / (double)1024.0F; + return d2 / d1; + } else { + return Double.parseDouble(nodeValue); + } + } + + private VectorPath getVectorPathFromNode(Node item) { + if (item.getNodeName().equals("path")) { + String pathData = null; + String fillColor = null; + + for(int j = 0; j < item.getAttributes().getLength(); ++j) { + Node node = item.getAttributes().item(j); + String name = node.getNodeName(); + String value = node.getNodeValue(); + if (name.equals("android:pathData")) { + pathData = this.normalizedPathData(value); + } else if (name.equals("android:fillColor")) { + try { + McStringUtils.toBytes(value); + fillColor = "#" + value; + } catch (Exception var9) { + fillColor = value; + } + } + } + + if (pathData != null) { + return new VectorPath(pathData, fillColor); + } + } + + return null; + } + + private String normalizedPathData(String value) { + StringBuilder sb = new StringBuilder(); + + for(int i = 0; i < value.length(); ++i) { + char ch = value.charAt(i); + if (ch == '.' && (i - 1 < 0 || !Character.isDigit(value.charAt(i - 1)))) { + sb.append('0'); + } + + sb.append(ch); + } + + return sb.toString(); + } + + private class VectorPath { + private String pathData; + private String fillColor; + + private VectorPath(String pathData, String fillColor) { + this.pathData = pathData; + this.fillColor = fillColor; + } + } + + private class Group { + private final List paths; + + public Group(List paths) { + this.paths = paths; + } + } + + private class AndroidVectorDrawable { + private final List paths; + private final List groups; + private final double height; + private final double width; + + private AndroidVectorDrawable(List paths, List groups, double width, double height) { + this.paths = paths; + this.groups = groups; + this.height = height; + this.width = width; + } + } +} diff --git a/src/main/java/com/mitac/cell/map/GeoCode.java b/src/main/java/com/mitac/cell/map/GeoCode.java new file mode 100644 index 0000000..7f8367c --- /dev/null +++ b/src/main/java/com/mitac/cell/map/GeoCode.java @@ -0,0 +1,34 @@ +package com.mitac.cell.map; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.mitac.cell.utils.McJsonUtils; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class GeoCode { + public static String getAddress(String apiKey, String latitude, String longitude) { + try { + String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=%s", latitude, longitude, apiKey); + OkHttpClient client = new OkHttpClient(); + Request request = (new Request.Builder()).url(url).build(); + Response responses = client.newCall(request).execute(); + JsonObject jResult = (JsonObject)McJsonUtils.toJsonElement(responses.body().byteStream()); + JsonObject jInfo = jResult.getAsJsonObject("info"); + String result = null; + if (jInfo.get("statuscode").getAsInt() == 0) { + JsonArray jLocations = jResult.getAsJsonArray("locations"); + if (jLocations.size() > 0) { + JsonObject jLocation = jLocations.get(0).getAsJsonObject(); + String.join(", ", jLocation.get("street").getAsString()); + result = jLocation.toString(); + } + } + + return result; + } catch (Exception var12) { + return null; + } + } +} diff --git a/src/main/java/com/mitac/cell/must/MustBuilder.java b/src/main/java/com/mitac/cell/must/MustBuilder.java new file mode 100644 index 0000000..fd726d2 --- /dev/null +++ b/src/main/java/com/mitac/cell/must/MustBuilder.java @@ -0,0 +1,165 @@ +package com.mitac.cell.must; + +import com.google.common.base.Strings; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonIOException; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.mitac.cell.data.McXml; +import com.mitac.cell.io.McEncryptedFileDrive; +import com.mitac.cell.io.McFile; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.LinkedHashMap; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; +import org.yaml.snakeyaml.Yaml; + +public class MustBuilder { + private static byte[] DEFAULT_KEY = "MUST@mitac".getBytes(); + private static String DEFAULT_SRC_FILE = "must.must"; + private String format; + private McFile sourceFile; + private McFile outputFile; + private JsonObject mustObject; + + public MustBuilder() { + } + + public MustBuilder(JsonObject mustObject) { + this.mustObject = mustObject; + } + + public McFile getSource() { + return this.sourceFile; + } + + public String getSourcePath() { + return this.sourceFile.getAbsolutePath(); + } + + public boolean setSource(String path) { + if (Strings.isNullOrEmpty(path)) { + this.sourceFile = new McFile(".", DEFAULT_SRC_FILE); + } else { + this.sourceFile = new McFile(path); + if (this.sourceFile.exists() && this.sourceFile.isDirectory()) { + this.sourceFile = new McFile(path, DEFAULT_SRC_FILE); + } + } + + return this.isSourceExists(); + } + + public boolean isSourceExists() { + return this.sourceFile != null && this.sourceFile.exists(); + } + + public String getFormat() { + if (Strings.isNullOrEmpty(this.format)) { + String ext = this.sourceFile.getExtension(); + if (Strings.isNullOrEmpty(ext)) { + this.format = "xml"; + } else { + ext = ext.toLowerCase(); + if (!ext.equals("json") && !ext.contentEquals("yaml")) { + this.format = "xml"; + } else { + this.format = ext; + } + } + } + + return this.format; + } + + public boolean setFormat(String format) { + if (!format.equals("xml") && !format.equals("json") && !format.equals("yaml")) { + return false; + } else { + this.format = format.trim().toLowerCase(); + return true; + } + } + + public McFile getOutput() { + return this.outputFile; + } + + public String getOutputPath() { + return this.outputFile.getAbsolutePath(); + } + + public void setOutput(String path) { + if (Strings.isNullOrEmpty(path)) { + this.outputFile = new McFile(this.sourceFile.getParent(), this.sourceFile.getNameWithoutExtension() + ".mst"); + } else { + this.outputFile = new McFile(path); + if (this.outputFile.exists() && this.outputFile.isDirectory()) { + this.outputFile = new McFile(path, this.sourceFile.getNameWithoutExtension() + ".mst"); + } + } + + } + + public boolean build() throws IOException, JsonIOException, JsonSyntaxException, ParserConfigurationException, SAXException { + this.mustObject = null; + String format = this.getFormat(); + if (format.equals("xml")) { + McXml xml = new McXml(); + this.mustObject = xml.load((File)this.sourceFile); + } else if (format.equals("json")) { + Reader reader = new FileReader(this.sourceFile); + JsonElement jElement = JsonParser.parseReader(reader); + if (jElement.isJsonObject()) { + this.mustObject = jElement.getAsJsonObject(); + } + } else if (format.equals("yaml")) { + Reader reader = new FileReader(this.sourceFile); + LinkedHashMap map = (LinkedHashMap)(new Yaml()).load(reader); + JsonElement jElement = (new GsonBuilder()).create().toJsonTree(map); + if (jElement.isJsonObject()) { + this.mustObject = jElement.getAsJsonObject(); + } + } + + return this.hasContents(); + } + + public boolean save(String destPath) { + this.setOutput(destPath); + McFile destFile = this.outputFile; + McEncryptedFileDrive drive = new McEncryptedFileDrive(destFile); + drive.enableInstantSave(false); + drive.setKey(DEFAULT_KEY); + drive.addFile("/must.must", this.mustObject.toString().getBytes()); + drive.save(); + return true; + } + + public boolean save() { + if (this.outputFile == null) { + this.setOutput((String)null); + } + + McFile destFile = this.outputFile; + McEncryptedFileDrive drive = new McEncryptedFileDrive(destFile); + drive.enableInstantSave(false); + drive.setKey(DEFAULT_KEY); + drive.addFile("/must.must", this.mustObject.toString().getBytes()); + drive.save(); + return true; + } + + public boolean hasContents() { + return this.mustObject != null && this.mustObject.size() > 0; + } + + public String toString() { + return this.hasContents() ? (new GsonBuilder()).setPrettyPrinting().create().toJson(this.mustObject) : "No configurations."; + } +} diff --git a/src/main/java/com/mitac/cell/net/McNetUtils.java b/src/main/java/com/mitac/cell/net/McNetUtils.java new file mode 100644 index 0000000..d220813 --- /dev/null +++ b/src/main/java/com/mitac/cell/net/McNetUtils.java @@ -0,0 +1,204 @@ +package com.mitac.cell.net; + +import com.google.common.base.Strings; +import com.google.common.io.BaseEncoding; +import com.mitac.cell.utils.McNumberUtils; +import com.mitac.cell.utils.McStringUtils; +import java.io.IOException; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class McNetUtils { + private static final String[] netMaskArray = new String[]{"255.255.255.255", "255.255.255.254", "255.255.255.252", "255.255.255.248", "255.255.255.240", "255.255.255.224", "255.255.255.192", "255.255.255.128", "255.255.255.0", "255.255.254.0", "255.255.252.0", "255.255.248.0", "255.255.240.0", "255.255.224.0", "255.255.192.0", "255.255.128.0", "255.255.0.0", "255.254.0.0", "255.252.0.0", "255.248.0.0", "255.240.0.0", "255.224.0.0", "255.192.0.0", "255.128.0.0", "255.0.0.0", "254.0.0.0", "252.0.0.0", "248.0.0.0", "240.0.0.0", "224.0.0.0", "192.0.0.0", "128.0.0.0", "0.0.0.0"}; + private static final Pattern IPv4RegexPattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.) {3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + + public static int toInt(String hostName) { + try { + InetAddress inetAddress = InetAddress.getByName(hostName); + ByteBuffer buffer = ByteBuffer.allocate(32); + buffer.put(inetAddress.getAddress()); + buffer.position(0); + return buffer.getInt(); + } catch (UnknownHostException e) { + e.printStackTrace(); + return -1; + } + } + + public static InetAddress toAddress(int ipAddress) { + byte[] byteArray = McNumberUtils.toBytes(4, false, ipAddress); + + try { + return InetAddress.getByAddress(byteArray); + } catch (UnknownHostException e) { + e.printStackTrace(); + return null; + } + } + + public static int toPrefixLength(String netMask) { + int prefixLength = 0; + + for(int i = 0; i < netMaskArray.length; ++i) { + if (netMaskArray[i].equals(netMask)) { + prefixLength = i; + break; + } + } + + return prefixLength; + } + + public static String toNetMask(int prefixLength) { + return netMaskArray[prefixLength]; + } + + public static long ipToLong(String ipAddress) { + try { + return ipToLong(InetAddress.getByName(ipAddress)); + } catch (UnknownHostException e) { + e.printStackTrace(); + return 0L; + } + } + + public static long ipToLong(InetAddress inetAddr) { + byte[] rawIp = inetAddr.getAddress(); + return (((long)rawIp[0] & 255L) << 24) + (((long)rawIp[1] & 255L) << 16) + (((long)rawIp[2] & 255L) << 8) + ((long)rawIp[3] & 255L); + } + + public static String longToIp(long i) { + return (i >> 24 & 255L) + "." + (i >> 16 & 255L) + "." + (i >> 8 & 255L) + "." + (i & 255L); + } + + public static String hostName() { + try { + String hostName = InetAddress.getLocalHost().getHostName(); + if (Strings.isNullOrEmpty(hostName)) { + hostName = System.getenv(System.getProperty("os.name").toLowerCase().startsWith("win") ? "COMPUTERNAME" : "HOSTNAME"); + } + + if (Strings.isNullOrEmpty(hostName)) { + Scanner s = (new Scanner(Runtime.getRuntime().exec("hostname").getInputStream())).useDelimiter("\\n"); + hostName = s.hasNext() ? s.next() : ""; + } + + return hostName; + } catch (UnknownHostException var2) { + } catch (IOException var3) { + } + + return null; + } + + public static boolean isVmMacAddress(byte[] mac) { + if (null == mac) { + return true; + } else if (mac.length != 6) { + return true; + } else { + byte[][] invalidMacs = new byte[][]{{0, 5, 105}, {0, 28, 20}, {0, 12, 41}, {0, 80, 86}, {8, 0, 39}, {10, 0, 39}, {0, 3, -1}, {0, 21, 93}}; + + for(byte[] invalid : invalidMacs) { + if (invalid[0] == mac[0] && invalid[1] == mac[1] && invalid[2] == mac[2]) { + return true; + } + } + + return false; + } + } + + public static String toMacAddressString(byte[] macAddrBytes) { + return BaseEncoding.base16().withSeparator(":", 2).encode(macAddrBytes); + } + + public static List macAddress() { + try { + Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); + List macList = new ArrayList(); + + while(netInterfaces.hasMoreElements()) { + NetworkInterface netInterface = (NetworkInterface)netInterfaces.nextElement(); + String displayName = netInterface.getDisplayName(); + if (!McStringUtils.containsIgnoreCase(displayName, "virtual adapter") && !McStringUtils.containsIgnoreCase(displayName, "bluetooth")) { + byte[] macAddr = netInterface.getHardwareAddress(); + if (macAddr != null && netInterface.isUp() && !netInterface.isLoopback() && macAddr.length == 6) { + macList.add(macAddr); + } + } + } + + return macList; + } catch (SocketException var5) { + return null; + } + } + + public static String getHost(String hostName) { + if (!Strings.isNullOrEmpty(hostName)) { + hostName = hostName.trim(); + if (Strings.isNullOrEmpty(hostName)) { + return null; + } else { + int indexPort = hostName.indexOf(":"); + return indexPort >= 0 ? hostName.substring(0, hostName.indexOf(":")) : hostName; + } + } else { + return null; + } + } + + public static byte[] getMacAddr() { + List macAddresses = macAddress(); + return macAddresses != null && macAddresses.size() > 0 ? (byte[])macAddress().get(0) : null; + } + + public static String ipAddress(InetAddress inetAddress) { + if (inetAddress == null) { + return null; + } else { + String address = inetAddress.toString(); + return Strings.isNullOrEmpty(address) ? null : address.split("/")[1]; + } + } + + public static String getIpAddress() { + String ip = null; + + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) { + NetworkInterface iface = (NetworkInterface)interfaces.nextElement(); + if (!iface.isLoopback() && iface.isUp()) { + Enumeration addresses = iface.getInetAddresses(); + + while(addresses.hasMoreElements()) { + InetAddress addr = (InetAddress)addresses.nextElement(); + if (!(addr instanceof Inet6Address)) { + ip = addr.getHostAddress(); + } + } + } + } + + return ip; + } catch (SocketException e) { + throw new RuntimeException(e); + } + } + + public static boolean validate(String ip) { + return IPv4RegexPattern.matcher(ip).matches(); + } +} diff --git a/src/main/java/com/mitac/cell/net/Uri.java b/src/main/java/com/mitac/cell/net/Uri.java new file mode 100644 index 0000000..c0f031a --- /dev/null +++ b/src/main/java/com/mitac/cell/net/Uri.java @@ -0,0 +1,33 @@ +package com.mitac.cell.net; + +import com.google.common.base.Strings; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +public class Uri { + private URI uri; + + public Uri(String uri) { + this.uri = URI.create(uri); + } + + public String[] paths() { + String path = this.uri.getPath(); + return Strings.isNullOrEmpty(path) ? new String[0] : this.uri.getPath().split("/"); + } + + public List getPathSegments() { + ArrayList list = new ArrayList(); + + for(String path : this.paths()) { + list.add(path); + } + + return list; + } + + public static Uri parse(String uri) { + return new Uri(uri); + } +} diff --git a/src/main/java/com/mitac/cell/security/McBase64.java b/src/main/java/com/mitac/cell/security/McBase64.java new file mode 100644 index 0000000..8530fd4 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/McBase64.java @@ -0,0 +1,32 @@ +package com.mitac.cell.security; + +import com.google.common.base.Strings; +import com.google.common.io.BaseEncoding; +import java.io.UnsupportedEncodingException; + +public class McBase64 { + public static String toBase64(String source) { + return Strings.isNullOrEmpty(source) ? null : toBase64(source.getBytes()); + } + + public static String toBase64(byte[] bytes) { + return bytes == null ? null : BaseEncoding.base64().encode(bytes); + } + + public static byte[] fromBase64(String source) { + return Strings.isNullOrEmpty(source) ? null : BaseEncoding.base64().decode(source); + } + + public static String fromBase64ToString(String source) { + if (Strings.isNullOrEmpty(source)) { + return null; + } else { + try { + return new String(fromBase64(source), "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } + } + } +} diff --git a/src/main/java/com/mitac/cell/security/McCrypto.java b/src/main/java/com/mitac/cell/security/McCrypto.java new file mode 100644 index 0000000..2cc4e73 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/McCrypto.java @@ -0,0 +1,511 @@ +package com.mitac.cell.security; + +import com.mitac.cell.security.cipher.McRc4; +import com.mitac.cell.utils.McConvert; +import com.mitac.cell.utils.McNumberUtils; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.Mac; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +public class McCrypto { + public static final int ENCRYPT_MODE = 1; + public static final int DECRYPT_MODE = 2; + private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; + private static final String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; + private static final String RANDOM_ALGORITHM = "SHA1PRNG"; + private int mKeyLength; + private String mAlgorithm; + private byte[] mKey; + private byte[] mSource; + private byte[] mTarget; + private byte[] mInitVector; + private byte[] mPrivateKey; + private int mCipherMode; + private byte[] mFileHeader; + + public McCrypto() { + this(1, "AES/CBC/PKCS5Padding", 128); + } + + public McCrypto(int cipherMode) { + this(cipherMode, "AES/CBC/PKCS5Padding", 128); + } + + public McCrypto(int cipherMode, String algorithm) { + this(cipherMode, algorithm, 128); + } + + public McCrypto(int cipherMode, String algorithm, int keyLength) { + this.mCipherMode = 1; + this.mCipherMode = cipherMode; + this.mKeyLength = keyLength; + this.mAlgorithm = algorithm; + } + + public void setFileHeader(byte[] header) { + this.mFileHeader = header; + } + + public void setFileHeader(String header) { + this.setFileHeader(header.getBytes()); + } + + public byte[] getFileHeader() { + return this.mFileHeader; + } + + public void setKey(String key) { + this.mKey = key.getBytes(); + } + + public void setKey(byte[] key) { + this.mKey = key; + } + + public void setSource(byte[] source) { + if (this.mCipherMode == 2) { + this.setSource((InputStream)(new ByteArrayInputStream(source))); + } else { + this.mSource = source; + } + + } + + public void setSource(String source) { + this.setSource(source.getBytes()); + } + + public void setSourcePath(String sourcePath) { + try { + this.setSource((InputStream)(new FileInputStream(sourcePath))); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + } + + public void setSource(InputStream sourceStream) { + try { + if (this.mCipherMode == 2) { + byte[] data = new byte[4]; + sourceStream.read(data, 0, 4); + if (data[0] != 109 || data[1] != 99) { + return; + } + + sourceStream.read(data, 0, 4); + int fileHeaderLength = McConvert.toInt(true, data); + if (fileHeaderLength > 0) { + this.mFileHeader = new byte[fileHeaderLength]; + sourceStream.read(this.mFileHeader, 0, fileHeaderLength); + } + + GZIPInputStream gzipInputStream = new GZIPInputStream(new BufferedInputStream(sourceStream)); + byte[] lenData = new byte[4]; + gzipInputStream.read(lenData); + int pkLen = McConvert.toInt(true, lenData); + if (pkLen > 0) { + this.mPrivateKey = new byte[pkLen]; + } + + gzipInputStream.read(lenData); + int ivLen = McConvert.toInt(true, lenData); + if (ivLen > 0) { + this.mInitVector = new byte[ivLen]; + } + + if (pkLen > 0) { + gzipInputStream.read(this.mPrivateKey); + } + + if (ivLen > 0) { + gzipInputStream.read(this.mInitVector); + } + + gzipInputStream.read(lenData); + int dataLen = McConvert.toInt(true, lenData); + if (dataLen > 0) { + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + data = new byte[512]; + + int n; + while((n = gzipInputStream.read(data)) != -1) { + byteStream.write(data, 0, n); + } + + this.mSource = byteStream.toByteArray(); + byteStream.close(); + } + + gzipInputStream.close(); + } else { + int size = sourceStream.available(); + this.mSource = new byte[size]; + sourceStream.read(this.mSource); + sourceStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public void save(String destinationPath) { + try { + FileOutputStream stream = new FileOutputStream(destinationPath); + stream.write(this.getBytes()); + stream.flush(); + stream.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private byte[] getEncryptedDataHeader() { + int size = 12; + int pkLen = 0; + int ivLen = 0; + if (this.mPrivateKey != null) { + pkLen = this.mPrivateKey.length; + } + + if (this.mInitVector != null) { + ivLen = this.mInitVector.length; + } + + byte[] header = new byte[size + pkLen + ivLen]; + size = 0; + byte[] lenData = McNumberUtils.toBytes(4, true, pkLen); + + for(byte b : lenData) { + header[size++] = b; + } + + lenData = McNumberUtils.toBytes(4, true, ivLen); + + for(byte b : lenData) { + header[size++] = b; + } + + if (pkLen > 0) { + for(byte b : this.mPrivateKey) { + header[size++] = b; + } + } + + if (ivLen > 0) { + for(byte b : this.mInitVector) { + header[size++] = b; + } + } + + lenData = McNumberUtils.toBytes(4, true, this.mTarget.length); + + for(byte b : lenData) { + header[size++] = b; + } + + return header; + } + + public InputStream getInputStream() { + return this.mTarget != null ? new ByteArrayInputStream(this.mTarget) : null; + } + + public byte[] getRaw() { + return this.mTarget; + } + + public byte[] getBytes() { + if (this.mCipherMode == 1) { + try { + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + byteStream.write(new byte[]{109, 99, 3, 1}); + if (this.mFileHeader != null) { + byteStream.write(McNumberUtils.toBytes(4, true, this.mFileHeader.length)); + byteStream.write(this.mFileHeader); + } else { + byteStream.write(new byte[4]); + } + + byteStream.size(); + GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteStream); + gzipOutputStream.write(this.getEncryptedDataHeader()); + gzipOutputStream.write(this.mTarget); + gzipOutputStream.flush(); + gzipOutputStream.close(); + return byteStream.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } else { + return this.mTarget; + } + } + + public byte[] getInitVector() { + return this.mInitVector; + } + + public byte[] getPrivateKey() { + return this.mPrivateKey; + } + + public byte[] run() { + return this.mCipherMode == 1 ? this.encrypt() : this.decrypt(); + } + + private byte[] encrypt() { + this.mTarget = null; + if (this.mAlgorithm.toUpperCase().equals("RC4")) { + this.mTarget = this.doByRc4(); + } else { + this.mTarget = this.doByCipher(1); + } + + return this.mTarget; + } + + private byte[] decrypt() { + this.mTarget = null; + if (this.mAlgorithm.toUpperCase().equals("RC4")) { + this.mTarget = this.doByRc4(); + } else { + this.mTarget = this.doByCipher(2); + } + + return this.mTarget; + } + + private void initCipher(Cipher cipher) throws InvalidKeyException, InvalidAlgorithmParameterException { + if (this.mCipherMode == 1 && !this.mAlgorithm.contains("ECB") && !this.mAlgorithm.contains("RSA")) { + this.mInitVector = this.generateIvSpec(); + } + + if (this.mAlgorithm.contains("AES")) { + if (this.mAlgorithm.contains("ECB")) { + cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength)); + } else { + cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength), new IvParameterSpec(this.mInitVector)); + } + } else if (this.mAlgorithm.contains("RSA")) { + cipher.init(this.mCipherMode, this.mCipherMode == 1 ? this.getRsaPublicKey() : this.getRsaPrivateKey(this.mPrivateKey)); + } else if (this.mAlgorithm.contains("DESede")) { + if (this.mAlgorithm.contains("ECB")) { + cipher.init(this.mCipherMode, this.getDesedeKey(this.mKey)); + } else { + cipher.init(this.mCipherMode, this.getDesedeKey(this.mKey), new IvParameterSpec(this.mInitVector)); + } + } else if (this.mAlgorithm.contains("DES")) { + if (this.mAlgorithm.contains("ECB")) { + cipher.init(this.mCipherMode, this.getDesKey(this.mKey)); + } else { + cipher.init(this.mCipherMode, this.getDesKey(this.mKey), new IvParameterSpec(this.mInitVector)); + } + } else if (this.mAlgorithm.contains("Blowfish")) { + if (this.mAlgorithm.contains("ECB")) { + cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength)); + } else { + cipher.init(this.mCipherMode, this.getAesKey(this.mKey, this.mKeyLength), new IvParameterSpec(this.mInitVector)); + } + } + + } + + private byte[] generateIvSpec() { + try { + int count = 16; + if (this.mAlgorithm.contains("DES")) { + count = 8; + } + + byte[] iv = new byte[count]; + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.nextBytes(iv); + return iv; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + return null; + } + } + + public Key getAesKey(byte[] key, int keyLength) { + byte[] SALT = encryptMessageByHmacMd5(key); + int ITERATION_COUNT = SALT.length % 10 * 10; + + try { + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); + char[] keyArray = new char[key.length]; + + for(int i = 0; i < key.length; ++i) { + keyArray[i] = (char)key[i]; + } + + PBEKeySpec keySpec = new PBEKeySpec(keyArray, SALT, ITERATION_COUNT, keyLength); + SecretKey tempKey = keyFactory.generateSecret(keySpec); + return new SecretKeySpec(tempKey.getEncoded(), this.mAlgorithm); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (InvalidKeySpecException e) { + e.printStackTrace(); + } + + return null; + } + + private Key getDesKey(byte[] key) { + try { + DESKeySpec keySpec = new DESKeySpec(key); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + return keyFactory.generateSecret(keySpec); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (InvalidKeySpecException e) { + e.printStackTrace(); + } + + return null; + } + + private Key getRsaPublicKey() { + try { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(this.mKeyLength); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + this.mPrivateKey = keyPair.getPrivate().getEncoded(); + return keyPair.getPublic(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + return null; + } + } + + private Key getRsaPrivateKey(byte[] keyBytes) { + try { + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); + return keyFactory.generatePrivate(keySpec); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (InvalidKeySpecException e) { + e.printStackTrace(); + } + + return null; + } + + private Key getDesedeKey(byte[] key) { + int len = 24; + byte[] newKey = new byte[len]; + System.arraycopy(key, 0, newKey, 0, Math.min(key.length, len)); + return new SecretKeySpec(newKey, "DESede"); + } + + private byte[] doByCipher(int cipherMode) { + try { + Cipher cipher = Cipher.getInstance(this.mAlgorithm); + this.initCipher(cipher); + this.mTarget = cipher.doFinal(this.mSource); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (NoSuchPaddingException e) { + e.printStackTrace(); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (InvalidAlgorithmParameterException e) { + e.printStackTrace(); + } catch (IllegalBlockSizeException e) { + e.printStackTrace(); + } catch (BadPaddingException e) { + e.printStackTrace(); + } + + return this.mTarget; + } + + private byte[] doByRc4() { + McRc4 cipher = new McRc4(this.mKey); + return cipher.decrypt(this.mSource); + } + + public static byte[] encryptMessageByHmacMd5(byte[] message) { + try { + Mac mac = Mac.getInstance("HmacMD5"); + mac.init(new SecretKeySpec(message, "HmacMD5")); + return mac.doFinal(message); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } + + return null; + } + + public static byte[] encryptMessageByMd5(String message) { + return message != null ? encryptMessageByMd5(message.getBytes()) : null; + } + + public static byte[] encryptMessageByMd5(byte[] message) { + try { + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + messageDigest.reset(); + return messageDigest.digest(message); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + return null; + } + } + + public static byte[] encryptByAES(byte[] key, byte[] src, int mode) { + try { + Provider bcProvider = new BouncyCastleProvider(); + SecretKeySpec skey = new SecretKeySpec(key, "AES"); + Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding", bcProvider); + cipher.init(mode == 0 ? 2 : 1, skey); + byte[] decrypted = cipher.doFinal(src); + return decrypted; + } catch (Exception var7) { + return null; + } + } +} diff --git a/src/main/java/com/mitac/cell/security/McOtaCert.java b/src/main/java/com/mitac/cell/security/McOtaCert.java new file mode 100644 index 0000000..08d88df --- /dev/null +++ b/src/main/java/com/mitac/cell/security/McOtaCert.java @@ -0,0 +1,66 @@ +package com.mitac.cell.security; + +import com.google.common.io.BaseEncoding; +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import org.apache.commons.io.IOUtils; + +public class McOtaCert { + private static final String DIGEST_ALGORITHM = "SHA-256"; + private static BaseEncoding Base64 = BaseEncoding.base64(); + private byte[] keyBytes = null; + private byte[] hashBytes = null; + + public McOtaCert(InputStream input) { + this.dispatch(input); + } + + public byte[] getKey() { + return this.keyBytes; + } + + public byte[] getHash() { + return this.hashBytes; + } + + public boolean sameKey(byte[] bytes) { + return Arrays.equals(bytes, this.getKey()); + } + + public boolean sameHash(String base64Hash) { + return base64Hash.equals(this.getBase64Hash()); + } + + public String getBase64Hash() { + return BaseEncoding.base64Url().encode(this.getHash()); + } + + private void dispatch(InputStream input) { + try { + String keyContent = IOUtils.toString(input, "UTF-8"); + keyContent = this.getKeyBody(keyContent); + this.keyBytes = Base64.decode(keyContent); + this.hashBytes = this.genHash(this.keyBytes); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private String getKeyBody(String keyContent) { + return keyContent.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "").replace("\n", "").replace("\r", ""); + } + + private byte[] genHash(byte[] bytes) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + return md.digest(bytes); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/com/mitac/cell/security/McTextEncryptor.java b/src/main/java/com/mitac/cell/security/McTextEncryptor.java new file mode 100644 index 0000000..dd3dd62 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/McTextEncryptor.java @@ -0,0 +1,87 @@ +package com.mitac.cell.security; + +import com.mitac.cell.utils.McStringUtils; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +public class McTextEncryptor { + private SecretKey secretKey; + private final Cipher decryptor; + + public McTextEncryptor(String password, String salt) { + PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), McStringUtils.toBytes(salt), 1024, 256); + SecretKey secretKey = this.newSecretKey("PBKDF2WithHmacSHA1", keySpec); + this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES"); + this.decryptor = this.newCipher("AES/CBC/PKCS5Padding"); + } + + public String decrypt(String encrypted) { + byte[] bytes = McStringUtils.toBytes(encrypted); + byte[] decryptedBytes = this.decrypt(bytes); + return decryptedBytes == null ? null : new String(decryptedBytes); + } + + public byte[] decrypt(byte[] encryptedBytes) { + synchronized(this.decryptor) { + byte[] iv = new byte[16]; + + byte[] var10000; + try { + this.decryptor.init(2, this.secretKey, new IvParameterSpec(iv)); + var10000 = this.decryptor.doFinal(encryptedBytes); + } catch (Exception var6) { + return null; + } + + return var10000; + } + } + + public String encrypt(String source) { + synchronized(this.decryptor) { + String var10000; + try { + byte[] iv = new byte[16]; + this.decryptor.init(1, this.secretKey, new IvParameterSpec(iv)); + byte[] bytes = this.decryptor.doFinal(source.getBytes()); + var10000 = McStringUtils.toHexString(bytes); + } catch (BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException var6) { + return null; + } + + return var10000; + } + } + + private Cipher newCipher(String algorithm) { + try { + return Cipher.getInstance(algorithm); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException("Not a valid encryption algorithm", e); + } catch (NoSuchPaddingException e) { + throw new IllegalStateException("Should not happen", e); + } + } + + private SecretKey newSecretKey(String algorithm, PBEKeySpec keySpec) { + try { + SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm); + return factory.generateSecret(keySpec); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException("Not a valid encryption algorithm", e); + } catch (InvalidKeySpecException e) { + throw new IllegalArgumentException("Not a valid secret key", e); + } + } +} diff --git a/src/main/java/com/mitac/cell/security/McUserAuthenticationProvider.java b/src/main/java/com/mitac/cell/security/McUserAuthenticationProvider.java new file mode 100644 index 0000000..7741cc4 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/McUserAuthenticationProvider.java @@ -0,0 +1,26 @@ +package com.mitac.cell.security; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; + +public class McUserAuthenticationProvider implements AuthenticationProvider { + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + boolean result = false; + if (result) { + List grantedAuthorities = new ArrayList(); + McUserAuthenticationToken auth = new McUserAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities); + return auth; + } else { + throw new BadCredentialsException("Bad User Credentials."); + } + } + + public boolean supports(Class authentication) { + return true; + } +} diff --git a/src/main/java/com/mitac/cell/security/McUserAuthenticationToken.java b/src/main/java/com/mitac/cell/security/McUserAuthenticationToken.java new file mode 100644 index 0000000..36c8cd7 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/McUserAuthenticationToken.java @@ -0,0 +1,26 @@ +package com.mitac.cell.security; + +import java.util.Collection; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; + +public class McUserAuthenticationToken extends AbstractAuthenticationToken { + private static final long serialVersionUID = 503883598783793420L; + private final Object principal; + private Object credentials; + + public McUserAuthenticationToken(Object principal, Object credentials, Collection authorities) { + super(authorities); + this.principal = principal; + this.credentials = credentials; + super.setAuthenticated(true); + } + + public Object getCredentials() { + return this.credentials; + } + + public Object getPrincipal() { + return this.principal; + } +} diff --git a/src/main/java/com/mitac/cell/security/cipher/McRc4.java b/src/main/java/com/mitac/cell/security/cipher/McRc4.java new file mode 100644 index 0000000..0e29fa1 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/cipher/McRc4.java @@ -0,0 +1,74 @@ +package com.mitac.cell.security.cipher; + +public class McRc4 { + private final byte[] mPermutationArray = new byte[256]; + private final byte[] mMixedArray = new byte[256]; + + public McRc4() { + } + + public McRc4(String key) { + this.setKey(key); + } + + public McRc4(byte[] key) { + this.setKey(key); + } + + public void setKey(String key) { + if (key != null) { + this.setKey(key.getBytes()); + } + } + + public void setKey(byte[] keyBytes) { + if (keyBytes != null) { + int keyLen = keyBytes.length; + if (keyLen >= 1 && keyLen <= 256) { + for(int i = 0; i < 256; ++i) { + this.mPermutationArray[i] = (byte)i; + this.mMixedArray[i] = keyBytes[i % keyLen]; + } + + int j = 0; + + for(int i = 0; i < 256; ++i) { + j = j + this.mPermutationArray[i] + this.mMixedArray[i] & 255; + byte[] var10000 = this.mPermutationArray; + var10000[i] ^= this.mPermutationArray[j]; + var10000 = this.mPermutationArray; + var10000[j] ^= this.mPermutationArray[i]; + var10000 = this.mPermutationArray; + var10000[i] ^= this.mPermutationArray[j]; + } + + } + } + } + + public byte[] encrypt(byte[] sourceData) { + byte[] encryptedData = new byte[sourceData.length]; + int i = 0; + int j = 0; + + for(int count = 0; count < sourceData.length; ++count) { + i = i + 1 & 255; + j = j + this.mPermutationArray[i] & 255; + byte[] var10000 = this.mPermutationArray; + var10000[i] ^= this.mPermutationArray[j]; + var10000 = this.mPermutationArray; + var10000[j] ^= this.mPermutationArray[i]; + var10000 = this.mPermutationArray; + var10000[i] ^= this.mPermutationArray[j]; + int t = this.mPermutationArray[i] + this.mPermutationArray[j] & 255; + int k = this.mPermutationArray[t]; + encryptedData[count] = (byte)(sourceData[count] ^ k); + } + + return encryptedData; + } + + public byte[] decrypt(byte[] encryptedData) { + return this.encrypt(encryptedData); + } +} diff --git a/src/main/java/com/mitac/cell/shell/McRuntime.java b/src/main/java/com/mitac/cell/shell/McRuntime.java new file mode 100644 index 0000000..c29f544 --- /dev/null +++ b/src/main/java/com/mitac/cell/shell/McRuntime.java @@ -0,0 +1,90 @@ +package com.mitac.cell.shell; + +import com.google.common.io.ByteStreams; +import com.google.common.io.CharStreams; +import com.mitac.cell.io.McFile; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; + +public class McRuntime { + private static Runtime runtime = Runtime.getRuntime(); + + public static Process exec(String... cmdArray) { + try { + return cmdArray.length == 1 ? runtime.exec(cmdArray[0]) : runtime.exec(cmdArray); + } catch (IOException var2) { + return null; + } + } + + public static InputStream execInputStream(String... cmdArray) { + Process process = exec(cmdArray); + return process == null ? null : process.getInputStream(); + } + + public static Reader execReader(String... cmdArray) { + InputStream is = execInputStream(cmdArray); + return is == null ? null : new InputStreamReader(is); + } + + public static byte[] execBytes(String... cmdArray) { + InputStream is = execInputStream(cmdArray); + if (is == null) { + return null; + } else { + try { + return ByteStreams.toByteArray(is); + } catch (IOException var3) { + return null; + } + } + } + + public static String execString(String... cmdArray) { + InputStream is = execInputStream(cmdArray); + if (is == null) { + return null; + } else { + try { + return CharStreams.toString(new InputStreamReader(is)); + } catch (IOException var3) { + return null; + } + } + } + + public static List execStrings(String... cmdArray) { + Reader reader = execReader(cmdArray); + if (reader == null) { + return null; + } else { + try { + List lines = new ArrayList(); + BufferedReader bufferReader = new BufferedReader(reader); + String line = null; + + while((line = bufferReader.readLine()) != null) { + lines.add(line); + } + + return lines; + } catch (IOException var5) { + return null; + } + } + } + + public static boolean execFile(String filePath, String... cmdArray) { + return execFile(new McFile(filePath), cmdArray); + } + + public static boolean execFile(McFile file, String... cmdArray) { + InputStream is = execInputStream(cmdArray); + return is != null ? file.write(is) : false; + } +} diff --git a/src/main/java/com/mitac/cell/system/HwInfo.java b/src/main/java/com/mitac/cell/system/HwInfo.java new file mode 100644 index 0000000..9e34c5b --- /dev/null +++ b/src/main/java/com/mitac/cell/system/HwInfo.java @@ -0,0 +1,173 @@ +package com.mitac.cell.system; + +import com.google.common.base.Strings; +import com.mitac.cell.net.McNetUtils; +import com.mitac.cell.shell.McRuntime; +import java.io.BufferedReader; +import java.io.Reader; +import java.lang.management.ManagementFactory; +import java.util.UUID; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +public class HwInfo { + private String computerName; + private int processors; + private String serialNo; + private UUID systemUuid; + private long maxMemory; + private long totalMemory; + private long freeMemory; + private Long physicalTotal; + private Long physicalFree; + + public HwInfo(OsInfo.OS_TYPE osType) { + this.retreiveDeviceInfo(osType); + MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); + + try { + ObjectName osObject = new ObjectName("java.lang", "type", "OperatingSystem"); + this.physicalTotal = (Long)beanServer.getAttribute(osObject, "TotalPhysicalMemorySize"); + this.physicalFree = (Long)beanServer.getAttribute(osObject, "FreePhysicalMemorySize"); + } catch (Exception var4) { + } + + Runtime runtime = Runtime.getRuntime(); + this.maxMemory = runtime.maxMemory(); + this.totalMemory = runtime.totalMemory(); + this.freeMemory = runtime.freeMemory(); + this.processors = runtime.availableProcessors(); + } + + private void retreiveDeviceInfo(OsInfo.OS_TYPE osType) { + switch (osType) { + case LINUX: + this.retrieveDeviceInfoInLinux(); + break; + case WINDOWS: + this.retrieveDeviceInfoInWindows(); + break; + case MAC: + this.retrieveDeviceInfoInMac(); + } + + } + + public String getComputerName() { + return this.computerName; + } + + public int getProcessors() { + return this.processors; + } + + public UUID getSystemUuid() { + return this.systemUuid; + } + + public String serialNo() { + return this.serialNo; + } + + public long getMaxMemory() { + return this.maxMemory; + } + + public long getTotalMemory() { + return this.totalMemory; + } + + public long getFreeMemory() { + return this.freeMemory; + } + + public long getPhysicalTotal() { + return this.physicalTotal; + } + + public long getPhysicalFree() { + return this.physicalFree; + } + + private void retrieveDeviceInfoInWindows() { + this.computerName = McNetUtils.hostName(); + if (Strings.isNullOrEmpty(this.computerName)) { + this.computerName = System.getenv("COMPUTERNAME"); + } + + try { + Reader reader = McRuntime.execReader("wmic", "csproduct", "get", "identifyingnumber, uuid"); + BufferedReader bufferedReader = new BufferedReader(reader); + + String line; + for(line = null; (line = bufferedReader.readLine()) != null && (Strings.isNullOrEmpty(line) || line.startsWith("IdentifyingNumber")); var6 = null) { + } + + if (line != null && line.length() >= 19) { + this.serialNo = line.substring(0, 19).trim(); + this.systemUuid = UUID.fromString(line.substring(19).trim()); + } + } catch (Exception var4) { + } + + } + + private void retrieveDeviceInfoInLinux() { + this.computerName = McNetUtils.hostName(); + + try { + Reader reader = McRuntime.execReader("dmidecode", "-t", "system"); + BufferedReader bufferedReader = new BufferedReader(reader); + String line = null; + + while((line = bufferedReader.readLine()) != null) { + if (Strings.isNullOrEmpty(line)) { + String var6 = null; + } else { + if (line.contains("Serial")) { + this.serialNo = line.substring(16).trim(); + if (this.serialNo.endsWith("O.E.M")) { + this.serialNo = null; + } + } else if (line.contains("UUID")) { + this.systemUuid = UUID.fromString(line.substring(7).trim()); + } + + if (!Strings.isNullOrEmpty(this.serialNo) && this.systemUuid != null) { + break; + } + } + } + } catch (Exception var4) { + } + + } + + private void retrieveDeviceInfoInMac() { + this.computerName = McNetUtils.hostName(); + + try { + Reader reader = McRuntime.execReader("/usr/sbin/system_profiler", "SPHardwareDataType"); + BufferedReader bufferedReader = new BufferedReader(reader); + String line = null; + + while((line = bufferedReader.readLine()) != null) { + if (!Strings.isNullOrEmpty(line) && !line.startsWith("IdentifyingNumber")) { + if (line.contains("Serial")) { + this.serialNo = line.substring(30).trim(); + } else if (line.contains("Hardware UUID")) { + this.systemUuid = UUID.fromString(line.substring(21).trim()); + } + + if (!Strings.isNullOrEmpty(this.serialNo) && this.systemUuid != null) { + break; + } + } else { + String var6 = null; + } + } + } catch (Exception var4) { + } + + } +} diff --git a/src/main/java/com/mitac/cell/system/McSystemInfo.java b/src/main/java/com/mitac/cell/system/McSystemInfo.java new file mode 100644 index 0000000..f01f7c1 --- /dev/null +++ b/src/main/java/com/mitac/cell/system/McSystemInfo.java @@ -0,0 +1,37 @@ +package com.mitac.cell.system; + +import com.mitac.cell.net.McNetUtils; +import java.util.List; + +public class McSystemInfo { + private OsInfo osInfo = new OsInfo(); + private HwInfo hwInfo; + private byte[] macAddr; + private List macAddresses; + + public McSystemInfo() { + this.hwInfo = new HwInfo(this.osInfo.osType()); + this.macAddresses = McNetUtils.macAddress(); + this.macAddr = McNetUtils.getMacAddr(); + } + + public OsInfo getOsInfo() { + return this.osInfo; + } + + public HwInfo getHwInfo() { + return this.hwInfo; + } + + public List getMacAddresses() { + return this.macAddresses; + } + + public byte[] getMacAddress() { + return this.macAddr; + } + + public String generateHash() { + return ""; + } +} diff --git a/src/main/java/com/mitac/cell/system/MsWindows.java b/src/main/java/com/mitac/cell/system/MsWindows.java new file mode 100644 index 0000000..240bc11 --- /dev/null +++ b/src/main/java/com/mitac/cell/system/MsWindows.java @@ -0,0 +1,68 @@ +package com.mitac.cell.system; + +import com.google.common.base.Strings; +import com.mitac.cell.shell.McRuntime; + +public class MsWindows { + private static final String REGQUERY_UTIL = "reg query "; + private static final String REGBINARY_TOKEN = "REG_BINARY"; + private static final String PRODUCT_KEY_CMD = "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v DigitalProductId"; + + public static String queryRegistry(String cmd, String token) { + String cmdOutput = McRuntime.execString(cmd); + if (Strings.isNullOrEmpty(cmdOutput)) { + return null; + } else { + int tokenIndex = cmdOutput.indexOf(token); + return tokenIndex < 0 ? null : cmdOutput.substring(tokenIndex + token.length()).trim(); + } + } + + public static String getProductKey() { + String fullPID = ""; + String encodedKey = ""; + if (queryRegistry("reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v DigitalProductId", "REG_BINARY") != null) { + fullPID = queryRegistry("reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v DigitalProductId", "REG_BINARY"); + } + + encodedKey = fullPID.substring(104, 134); + char[] digits = new char[]{'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9'}; + int D_LEN = 29; + int S_LEN = 15; + int[] hexDigitalPID = new int[29]; + char[] des = new char[30]; + int i = 0; + int n = 0; + int hn = 0; + String rval = ""; + + for(int var12 = 0; var12 <= 14; ++var12) { + String var10002 = encodedKey.substring(var12 * 2, var12 * 2 + 2); + hexDigitalPID[var12] = Integer.decode("0x" + var10002); + } + + for(int var13 = 28; var13 >= 0; --var13) { + if ((var13 + 1) % 6 == 0) { + des[var13] = '-'; + } else { + hn = 0; + + for(int var15 = 14; var15 >= 0; --var15) { + hn = (hn << 8) + hexDigitalPID[var15]; + hexDigitalPID[var15] = hn / 24; + hn %= 24; + } + + des[var13] = digits[hn]; + } + } + + des[29] = '\n'; + + for(int var14 = 0; des[var14] != '\n'; ++var14) { + rval = rval + des[var14]; + } + + return rval; + } +} diff --git a/src/main/java/com/mitac/cell/system/OsInfo.java b/src/main/java/com/mitac/cell/system/OsInfo.java new file mode 100644 index 0000000..dd03778 --- /dev/null +++ b/src/main/java/com/mitac/cell/system/OsInfo.java @@ -0,0 +1,88 @@ +package com.mitac.cell.system; + +import java.io.File; + +public class OsInfo { + private OS_TYPE osType; + private String name = System.getProperty("os.name"); + private String version; + + public OsInfo() { + if (this.name != null) { + this.name = this.name.toLowerCase(); + } + + this.version = System.getProperty("os.version"); + if (this.name.contains("nux")) { + this.osType = OsInfo.OS_TYPE.LINUX; + } else if (this.name.contains("win")) { + this.osType = OsInfo.OS_TYPE.WINDOWS; + } else if (!this.name.contains("mac") && !this.name.contains("darwin")) { + if (!this.name.contains("nix") && !this.name.contains("aix")) { + if (this.name.contains("sunos")) { + this.osType = OsInfo.OS_TYPE.SOLARIS; + } else { + this.osType = OsInfo.OS_TYPE.UNKNOWN; + } + } else { + this.osType = OsInfo.OS_TYPE.AIX; + } + } else { + this.osType = OsInfo.OS_TYPE.MAC; + } + + if (this.osType == OsInfo.OS_TYPE.WINDOWS) { + MsWindows.getProductKey(); + } + + } + + public OS_TYPE osType() { + return this.osType; + } + + public String getAppDataFolderPath() { + if (this.osType == OsInfo.OS_TYPE.WINDOWS) { + return System.getenv("AppData"); + } else if (this.osType == OsInfo.OS_TYPE.LINUX) { + return System.getProperty("user.home"); + } else { + return this.osType == OsInfo.OS_TYPE.MAC ? "/" : "/"; + } + } + + public File getAppDataFolderPath(String appName) { + return new File(this.getAppDataFolderPath(), appName); + } + + public String getConfigFolderPath() { + if (this.osType == OsInfo.OS_TYPE.WINDOWS) { + return "c:\\ProgramData"; + } else if (this.osType == OsInfo.OS_TYPE.LINUX) { + return "/etc"; + } else { + return this.osType == OsInfo.OS_TYPE.MAC ? "/" : "/"; + } + } + + public File getConfigFolder(String appName) { + return new File(this.getConfigFolderPath(), appName); + } + + public String name() { + return this.name; + } + + public String version() { + return this.version; + } + + public static enum OS_TYPE { + WINDOWS, + LINUX, + SOLARIS, + MAC, + AIX, + UNKNOWN; + } +} diff --git a/src/main/java/com/mitac/cell/utils/McBooleanUtils.java b/src/main/java/com/mitac/cell/utils/McBooleanUtils.java new file mode 100644 index 0000000..522bf9a --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McBooleanUtils.java @@ -0,0 +1,28 @@ +package com.mitac.cell.utils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class McBooleanUtils { + private static final List falseValues = new ArrayList() { + { + Object[] trueValues = new Object[]{'f', 'n', 'x', '0', "false", "no", "not", "off", "down", "stop", "cancel", "disable", "disabled", "negative"}; + this.addAll(Arrays.asList(trueValues)); + } + }; + + public static Boolean isTrue(Object value) { + if (value == null) { + return false; + } else if (value instanceof Boolean) { + return (Boolean)value; + } else if (value instanceof Character) { + return !falseValues.contains(Character.toLowerCase((Character)value)); + } else if (value instanceof String) { + return !falseValues.contains(((String)value).toLowerCase()); + } else { + return value instanceof Number ? ((Number)value).doubleValue() != (double)0.0F : false; + } + } +} diff --git a/src/main/java/com/mitac/cell/utils/McChar.java b/src/main/java/com/mitac/cell/utils/McChar.java new file mode 100644 index 0000000..2068340 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McChar.java @@ -0,0 +1,6 @@ +package com.mitac.cell.utils; + +public class McChar { + public static final char CHAR_SPACE = ' '; + public static final char CHAR_COMMA = ','; +} diff --git a/src/main/java/com/mitac/cell/utils/McCipherUtils.java b/src/main/java/com/mitac/cell/utils/McCipherUtils.java new file mode 100644 index 0000000..b087173 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McCipherUtils.java @@ -0,0 +1,47 @@ +package com.mitac.cell.utils; + +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import javax.crypto.Cipher; + +public class McCipherUtils { + public static final String RSA_OAEPWITHSHA1_MODE = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding"; + + public static String encryptByRsaPublicKey(String encryptMode, String publicKeyBase64, String plainText) { + try { + byte[] decoded = Base64.getDecoder().decode(publicKeyBase64); + X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded); + KeyFactory kf = KeyFactory.getInstance("RSA"); + RSAPublicKey rsaPublicKey = (RSAPublicKey)kf.generatePublic(spec); + Cipher cipher = Cipher.getInstance(encryptMode); + cipher.init(1, rsaPublicKey); + byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); + return Base64.getEncoder().encodeToString(encryptedBytes); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static boolean decryptByPrivateKey(String decryptMode, String privateKeyBase64, String encrpytString, String serialNo) { + try { + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBase64.getBytes(StandardCharsets.UTF_8))); + KeyFactory kf = KeyFactory.getInstance("RSA"); + RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)kf.generatePrivate(keySpec); + byte[] decodedString = Base64.getDecoder().decode(encrpytString.getBytes(StandardCharsets.UTF_8)); + Cipher cipher = Cipher.getInstance(decryptMode); + cipher.init(2, rsaPrivateKey); + byte[] decryptBytes = cipher.doFinal(decodedString); + String[] decryptStrings = (new String(decryptBytes)).split(","); + return decryptStrings.length == 3 && decryptStrings[0].equals(serialNo); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } +} diff --git a/src/main/java/com/mitac/cell/utils/McConvert.java b/src/main/java/com/mitac/cell/utils/McConvert.java new file mode 100644 index 0000000..79965cf --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McConvert.java @@ -0,0 +1,290 @@ +package com.mitac.cell.utils; + +import com.google.common.base.Strings; +import com.google.gson.JsonPrimitive; +import com.mitac.cell.doc.Csv; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.StreamCorruptedException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class McConvert { + public static String toString(Object value) { + return value.toString(); + } + + public static int toInt(String value) { + if (!value.startsWith("x") && !value.startsWith("0x")) { + try { + return NumberFormat.getInstance(Locale.ENGLISH).parse(value).intValue(); + } catch (ParseException e) { + e.printStackTrace(); + return -1; + } + } else { + value = value.substring(value.indexOf("x") + 1); + return Integer.parseInt(value, 16); + } + } + + public static int toInt(Object value) { + if (value == null) { + return 0; + } else if (value instanceof Number) { + return ((Number)value).intValue(); + } else { + try { + return Integer.parseInt(value.toString().trim()); + } catch (NumberFormatException var2) { + return 0; + } + } + } + + public static short toShort(Object value) { + if (value == null) { + return 0; + } else { + return value instanceof Number ? ((Number)value).shortValue() : Short.parseShort(value.toString()); + } + } + + public static long toLong(Object value) { + if (value == null) { + return 0L; + } else { + return value instanceof Number ? ((Number)value).longValue() : Long.parseLong(value.toString()); + } + } + + public static float toFloat(Object value) { + if (value == null) { + return 0.0F; + } else { + return value instanceof Number ? ((Number)value).floatValue() : Float.parseFloat(value.toString()); + } + } + + public static double toDouble(Object value) { + if (value == null) { + return (double)0.0F; + } else { + return value instanceof Number ? ((Number)value).doubleValue() : Double.parseDouble(value.toString()); + } + } + + public static boolean toBoolean(Object value) { + if (value == null) { + return false; + } else if (value instanceof Boolean) { + return (Boolean)value; + } else if (value instanceof Number) { + return toInt(value) != 0; + } else if (value instanceof String) { + String val = ((String)value).toLowerCase(); + return !val.isEmpty() && !val.equals("0") && !val.equals("false") && !val.equals("n") && !val.equals("no") && !val.equals("off") && !val.equals("stop") && !val.equals("down"); + } else { + return value instanceof JsonPrimitive ? ((JsonPrimitive)value).getAsBoolean() : false; + } + } + + public static byte[] toBlob(Object value) { + if (value == null) { + return null; + } else { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream output = new ObjectOutputStream(bos); + output.writeObject(value); + return bos.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + } + + public static String toCSVString(String[] values) { + Csv formatter = new Csv(); + return formatter.toString(values); + } + + public static String toCSVString(int[] values) { + StringBuilder sb = new StringBuilder(); + + for(int i = 0; i < values.length; ++i) { + if (i > 0) { + sb.append(","); + } + + sb.append(values[i]); + } + + return sb.toString(); + } + + public static Object[] toObjectArray(int[] values) { + Object[] array = new Object[values.length]; + + for(int i = 0; i < values.length; ++i) { + array[i] = values[i]; + } + + return array; + } + + public static String toCSVString(List columns) { + Csv formatter = new Csv(); + return formatter.toString(columns); + } + + public static String toCSVString(Set columns) { + Csv formatter = new Csv(); + return formatter.toString(columns); + } + + public static String[] CSVtoStringArray(String csvString) { + Csv formatter = new Csv(); + + try { + return formatter.parse(csvString); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static Set CSVtoStringSet(String csvString) { + return new HashSet(CSVtoStringList(csvString)); + } + + public static List CSVtoStringList(String csvString) { + Csv formatter = new Csv(); + + try { + return Arrays.asList(formatter.parse(csvString)); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static byte[] toBytes(int size, boolean isLittleEndian, int value) { + return ByteBuffer.allocate(size).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).putInt(value).array(); + } + + public static int toInt(boolean isLittleEndian, byte[] value) { + return ByteBuffer.wrap(value).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).getInt(); + } + + public static byte[] toBytes(Object object) { + if (object == null) { + return null; + } else { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutput out = new ObjectOutputStream(bos); + out.writeObject(object); + return bos.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + } + + public static Object toObject(byte[] object) { + if (object == null) { + return null; + } else { + try { + ByteArrayInputStream bis = new ByteArrayInputStream(object); + ObjectInput in = new ObjectInputStream(bis); + return in.readObject(); + } catch (StreamCorruptedException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + + return null; + } + } + + public static int[] toIntArray(byte[] byteArray) { + if (byteArray == null) { + return null; + } else { + int[] intArray = new int[byteArray.length]; + + for(int i = 0; i < byteArray.length; intArray[i] = byteArray[i++] & 255) { + } + + return intArray; + } + } + + public static int toInt(byte[] byteArray) { + int value = 0; + + for(int i = 0; i < byteArray.length; ++i) { + int shift = (byteArray.length - 1 - i) * 8; + value += (byteArray[i] & 255) << shift; + } + + return value; + } + + public static String toJavaString(String source) { + if (Strings.isNullOrEmpty(source)) { + return ""; + } else { + String replaced = source.replace("\\r", "\r").replace("\\n", "\n").replace("\\t", "\t").replace("\\b", "\b").replace("\\f", "\f").replace("\\'", "'").replace("\\\"", "\"").replace("\\\\", "\\"); + Pattern p = Pattern.compile("\\\\[uU][A-Fa-f0-9]{4}"); + Matcher matcher = p.matcher(replaced); + + for(int pos = 0; matcher.find(pos); pos = matcher.end()) { + Integer v = Integer.parseInt(matcher.group(0).substring(2), 16); + replaced = replaced.replace(matcher.group(0), String.format("%c", v)); + } + + return replaced; + } + } + + public static String toNormalString(String source) { + return source.replace("\n", "\\n").replace("\t", "\\t").replace("\b", "\\b").replace("\f", "\\f"); + } + + public static String toInversedString(String source) { + StringBuilder sb = new StringBuilder(source); + + for(int index = 0; index < sb.length(); ++index) { + char c = sb.charAt(index); + if (Character.isLowerCase(c)) { + sb.setCharAt(index, Character.toUpperCase(c)); + } else { + sb.setCharAt(index, Character.toLowerCase(c)); + } + } + + return sb.toString(); + } +} diff --git a/src/main/java/com/mitac/cell/utils/McDateTimeUtils.java b/src/main/java/com/mitac/cell/utils/McDateTimeUtils.java new file mode 100644 index 0000000..95971f0 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McDateTimeUtils.java @@ -0,0 +1,171 @@ +package com.mitac.cell.utils; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; +import org.apache.poi.ss.usermodel.DateUtil; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.joda.time.Days; +import org.joda.time.LocalDateTime; +import org.joda.time.Years; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class McDateTimeUtils { + public static final int START_TW_YEAR = 1911; + public static final String LONG_FORMAT = "yyyy-MM-dd HH:mm:ss"; + public static final String SHORT_FORMAT = "yyyy-MM-dd"; + public static final DateFormat SHORT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + public static boolean isBetween(DateTime startDate, DateTime endDate) { + return isBetween(startDate, endDate, new DateTime()); + } + + public static boolean isBetween(DateTime startDate, DateTime endDate, DateTime curDateTime) { + long mills = curDateTime.getMillis(); + return startDate.getMillis() <= mills && mills <= endDate.getMillis(); + } + + public static int yearsFrom(DateTime birthDate) { + return yearsBetween(birthDate, new DateTime()); + } + + public static int yearsBetween(DateTime fromDate, DateTime toDate) { + return Years.yearsBetween(fromDate.toLocalDate(), toDate.toLocalDate()).getYears(); + } + + public static int daysFrom(DateTime fromDate) { + return daysBetween(fromDate, new DateTime()); + } + + public static int daysBetween(DateTime fromDate, DateTime toDate) { + return Days.daysBetween(fromDate.toLocalDate(), toDate.toLocalDate()).getDays(); + } + + public static Date later(long millis) { + return DateTime.now().plus(millis).toDate(); + } + + public static Date secondsLater(int mins) { + return DateTime.now().plusSeconds(mins).toDate(); + } + + public static Date minsLater(int millis) { + return DateTime.now().plusMinutes(millis).toDate(); + } + + public static boolean isSameDate(DateTime date1, DateTime date2) { + return date1 != null && date2 != null ? date1.toLocalDate().equals(date2.toLocalDate()) : false; + } + + public static boolean isSameDate(Long date1, Long date2) { + return date1 != null && date2 != null ? isSameDate(new DateTime(date1, DateTimeZone.getDefault()), new DateTime(date2, DateTimeZone.getDefault())) : false; + } + + public static boolean isSameDay(DateTime date1, DateTime date2) { + if (date1 != null && date2 != null) { + return date1.getMonthOfYear() == date2.getMonthOfYear() && date1.getDayOfMonth() == date2.getDayOfMonth(); + } else { + return false; + } + } + + public static boolean isSameDay(Long date1, Long date2) { + return date1 != null && date2 != null ? isSameDay(new DateTime(date1, DateTimeZone.UTC), new DateTime(date2, DateTimeZone.UTC)) : false; + } + + public static boolean isSameDay(Date date1, String date2, String dateFormat) { + return date1 != null && !McStringUtils.isNullOrEmpty(date2) ? (new SimpleDateFormat(dateFormat)).format(date1).equals(date2) : false; + } + + public static String toString(DateTime dateTime, String dateFormat) { + if (dateTime == null) { + return null; + } else { + return dateFormat == null ? dateTime.toString() : DateTimeFormat.forPattern(dateFormat).print(dateTime); + } + } + + public static String toString(Date dateTime, TimeZone timeZone, String dateFormat) { + return toString(new DateTime(dateTime, DateTimeZone.forTimeZone(timeZone)), dateFormat); + } + + public static DateTime parseDate(String dateString, String dateFormat) { + return parseDate(dateString, dateFormat, DateTimeZone.UTC); + } + + public static DateTime parseDate(String dateString, String dateFormat, String timeZoneText) { + if (McStringUtils.isNullOrEmpty(dateString)) { + return null; + } else { + try { + DateTimeZone timeZone = McStringUtils.isNullOrEmpty(timeZoneText) ? DateTimeZone.UTC : DateTimeZone.forID(timeZoneText); + return parseDate(dateString, dateFormat, timeZone); + } catch (Exception var4) { + return parseDate(dateString, dateFormat, DateTimeZone.UTC); + } + } + } + + public static DateTime parseDate(String dateString, String dateFormat, DateTimeZone timeZone) { + if (McStringUtils.isNullOrEmpty(dateString)) { + return null; + } else { + if (timeZone == null) { + timeZone = DateTimeZone.UTC; + } + + try { + return McStringUtils.isNullOrEmpty(dateFormat) ? ISODateTimeFormat.dateTime().withZone(timeZone).parseDateTime(dateString) : DateTime.parse(dateString, DateTimeFormat.forPattern(dateFormat).withZone(timeZone)); + } catch (Exception var4) { + return null; + } + } + } + + public static DateTime parseTwDate(String twDateString) { + return McStringUtils.isNullOrEmpty(twDateString) ? null : parseTwDate(twDateString, "yyyy/MM/dd"); + } + + public static DateTime parseTwDate(String twDateString, String format) { + if (McStringUtils.isNullOrEmpty(twDateString)) { + return null; + } else { + int yearIndex = format.indexOf("yyyy"); + String yearString = twDateString.substring(yearIndex, 4); + int year = McNumberUtils.toInt(yearString) + 1911; + twDateString = twDateString.replaceFirst(yearString, String.valueOf(year)); + DateTimeFormatter formatter = DateTimeFormat.forPattern(format); + return DateTime.parse(twDateString, formatter); + } + } + + public static DateTime parseExcelDate(String cellValue) { + return McStringUtils.isNullOrEmpty(cellValue) ? null : parseExcelDate(Double.parseDouble(cellValue)); + } + + public static DateTime parseExcelDate(double cellValue) { + return new DateTime(DateUtil.getJavaDate(cellValue)); + } + + public static DateTime getUtcTime() { + return DateTime.now(DateTimeZone.UTC); + } + + public static DateTime toLocalTime(long utc, DateTimeZone timeZone) { + return (new LocalDateTime(utc, DateTimeZone.UTC)).toDateTime(timeZone); + } + + public static enum FREQUENCY { + second, + minute, + hour, + day, + week, + month, + year; + } +} diff --git a/src/main/java/com/mitac/cell/utils/McEmailUtils.java b/src/main/java/com/mitac/cell/utils/McEmailUtils.java new file mode 100644 index 0000000..f497801 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McEmailUtils.java @@ -0,0 +1,56 @@ +package com.mitac.cell.utils; + +import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.regex.Pattern; +import javax.mail.internet.InternetAddress; + +public class McEmailUtils { + private static final String EMAIL_REGEX = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z]+$"; + private static final Pattern emailPattern = Pattern.compile("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z]+$"); + + public static boolean isValid(String email) { + return McStringUtils.isNullOrEmpty(email) ? false : emailPattern.matcher(email).matches(); + } + + public static String formattedMail(String email, String name) { + if (isValid(email)) { + if (McStringUtils.isNullOrEmpty(name)) { + name = email.substring(0, email.indexOf(64)); + } + + return String.format("%s<%s>", name, email); + } else { + return null; + } + } + + public static List parseMails(String to) { + if (Strings.isNullOrEmpty(to)) { + return null; + } else { + List mails = new ArrayList(); + String delim = "\n\r\t;"; + StringTokenizer st = new StringTokenizer(to, "\n\r\t;"); + + while(st.hasMoreTokens()) { + String token = st.nextToken().trim().toLowerCase(); + + try { + InternetAddress[] address = InternetAddress.parse(token); + + for(InternetAddress addr : address) { + if (isValid(addr.getAddress())) { + mails.add(addr); + } + } + } catch (Exception var10) { + } + } + + return mails; + } + } +} diff --git a/src/main/java/com/mitac/cell/utils/McJsonUtils.java b/src/main/java/com/mitac/cell/utils/McJsonUtils.java new file mode 100644 index 0000000..ccb6467 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McJsonUtils.java @@ -0,0 +1,306 @@ +package com.mitac.cell.utils; + +import com.fatboyindustrial.gsonjodatime.Converters; +import com.google.common.base.Charsets; +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSyntaxException; +import com.google.gson.annotations.Expose; +import com.mitac.cell.gson.typeAdapter.CipherTypeAdapter; +import com.mitac.cell.gson.typeAdapter.CompatibleTimeZoneTypeAdapter; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import java.util.UUID; +import javax.crypto.Cipher; +import javax.servlet.http.HttpServletRequest; + +public class McJsonUtils { + public static String FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + private static final Gson gson; + private static final Gson gsonCloner; + + public static String getString(JsonObject jInfo, String property) { + JsonElement element = getProperty(jInfo, property); + if (element == null) { + return null; + } else { + return element.isJsonPrimitive() ? element.getAsString() : element.toString(); + } + } + + public static int getInt(JsonObject jInfo, String property, int defaultValue) { + JsonElement element = getProperty(jInfo, property); + return element == null ? defaultValue : element.getAsInt(); + } + + public static long getLong(JsonObject jInfo, String property, long defaultValue) { + JsonElement element = getProperty(jInfo, property); + return element == null ? defaultValue : element.getAsLong(); + } + + public static float getFloat(JsonObject jInfo, String property, float defaultValue) { + JsonElement element = getProperty(jInfo, property); + return element == null ? defaultValue : element.getAsFloat(); + } + + public static boolean getBoolean(JsonObject jInfo, String property, boolean defaultValue) { + JsonElement element = getProperty(jInfo, property); + return element == null ? defaultValue : element.getAsBoolean(); + } + + public static Date getDate(JsonObject jInfo, String property, Date defaultValue) { + JsonElement element = getProperty(jInfo, property); + return element == null ? defaultValue : new Date(element.getAsLong()); + } + + public static URL getUrl(JsonObject jInfo, String property) { + JsonElement element = getProperty(jInfo, property); + + try { + return element == null ? null : new URL(element.getAsString()); + } catch (MalformedURLException e) { + e.printStackTrace(); + return null; + } + } + + public static UUID getUuid(JsonObject jInfo, String property) { + JsonElement element = getProperty(jInfo, property); + return element == null ? null : UUID.fromString(element.getAsString()); + } + + public static JsonElement getProperty(JsonObject jInfo, String property) { + if (jInfo == null) { + jInfo = new JsonObject(); + } + + return jInfo == null ? null : jInfo.get(property); + } + + public static boolean isValid(JsonObject jObject) { + return !isNullOrEmpty(jObject); + } + + public static boolean isNullOrEmpty(JsonObject jObject) { + return jObject == null || jObject.entrySet().isEmpty(); + } + + public static JsonElement toJson(byte[] content) { + return content == null ? null : JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(content))); + } + + public static JsonElement toJsonElement(Object src) { + return gsonCloner.toJsonTree(src); + } + + public static void setProperty(JsonObject jInfo, String property, Object value) { + if (jInfo == null) { + jInfo = new JsonObject(); + } + + jInfo.add(property, toJsonElement(value)); + } + + public static JsonElement toJsonElement(String jsonSource) { + try { + return McStringUtils.isNullOrEmpty(jsonSource) ? null : JsonParser.parseString(jsonSource); + } catch (JsonSyntaxException var2) { + return null; + } + } + + public static JsonElement toJsonElement(HttpServletRequest request) { + try { + return toJsonElement((InputStream)request.getInputStream()); + } catch (Exception var2) { + return null; + } + } + + public static JsonElement toJsonElement(InputStream is) { + return is == null ? null : toJsonElement((Reader)(new InputStreamReader(is, Charsets.UTF_8))); + } + + public static JsonElement toJsonElement(File file) { + try { + return file != null && file.exists() && !file.isDirectory() ? toJsonElement((InputStream)(new FileInputStream(file))) : null; + } catch (FileNotFoundException e) { + e.printStackTrace(); + return null; + } + } + + public static JsonElement toJsonElement(Reader jsonReader) { + try { + return jsonReader == null ? null : JsonParser.parseReader(jsonReader); + } catch (Exception var2) { + return null; + } + } + + public static Map toBooleanMap(String jsonSource) { + if (McStringUtils.isNullOrEmpty(jsonSource)) { + return null; + } else { + JsonElement jElement = toJsonElement(jsonSource); + return jElement.isJsonObject() ? toBooleanMap(jElement.getAsJsonObject()) : null; + } + } + + public static Map toBooleanMap(JsonObject jObject) { + if (jObject != null && !jObject.entrySet().isEmpty()) { + Map map = new HashMap(); + + for(Map.Entry jEntry : jObject.entrySet()) { + boolean value = false; + if (((JsonElement)jEntry.getValue()).isJsonPrimitive()) { + JsonPrimitive jPrimitive = ((JsonElement)jEntry.getValue()).getAsJsonPrimitive(); + if (jPrimitive.isBoolean()) { + value = jPrimitive.getAsBoolean(); + } else if (jPrimitive.isNumber()) { + value = jPrimitive.getAsDouble() != (double)0.0F; + } else if (jPrimitive.isString()) { + value = McBooleanUtils.isTrue(jPrimitive.getAsString()); + } + } + + map.put((String)jEntry.getKey(), value); + } + + return map; + } else { + return null; + } + } + + public static Object toObject(HttpServletRequest request, Type dataType) { + try { + return toObject(toJsonElement((InputStream)request.getInputStream()), dataType); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static Object toObject(InputStream is, Type dataType) { + return toObject(toJsonElement(is), dataType); + } + + public static Object toObject(byte[] bytes, Type dataType) { + return toObject((InputStream)(new ByteArrayInputStream(bytes)), dataType); + } + + public static Object toObject(String jElement, Type dataType) { + return toObject(toJsonElement(jElement), dataType); + } + + public static Object toObject(JsonElement jElement, Type dataType) { + return jElement != null && !jElement.isJsonPrimitive() ? gson.fromJson(jElement, dataType) : null; + } + + public static Object clone(Object object) { + return gsonCloner.fromJson(toJsonElement(object), object.getClass()); + } + + public static String toJson(Object object) { + return gson.toJson(object); + } + + public static String toJson(Object object, boolean pretty) { + GsonBuilder builder = new GsonBuilder(); + if (pretty) { + builder.setPrettyPrinting(); + } + + return builder.create().toJson(object); + } + + public static JsonObject merge(JsonObject... jObjects) { + if (jObjects != null && jObjects.length != 0) { + JsonObject jResult = null; + + for(JsonObject jObject : jObjects) { + if (jResult == null) { + jResult = jObject; + } else { + for(Map.Entry entry : jObject.entrySet()) { + jResult.add((String)entry.getKey(), (JsonElement)entry.getValue()); + } + } + } + + return jResult; + } else { + return null; + } + } + + public static boolean equals(JsonElement src, JsonElement target) { + if (src != null && target != null) { + if (src.isJsonObject()) { + if (target.isJsonObject()) { + } + + return false; + } else if (src.isJsonArray()) { + if (target.isJsonObject()) { + } + + return false; + } else if (src.isJsonPrimitive()) { + if (!target.isJsonPrimitive()) { + return false; + } else { + JsonPrimitive srcPrim = src.getAsJsonPrimitive(); + JsonPrimitive targetPrim = target.getAsJsonPrimitive(); + if (srcPrim.isString()) { + return targetPrim.isString() && src.getAsString().equals(targetPrim.getAsString()); + } else if (srcPrim.isNumber()) { + return targetPrim.isNumber() && src.getAsDouble() == targetPrim.getAsDouble(); + } else { + return targetPrim.isBoolean() && src.getAsBoolean() == targetPrim.getAsBoolean(); + } + } + } else { + return src.isJsonNull() && target.isJsonNull(); + } + } else { + return false; + } + } + + static { + gson = Converters.registerDateTime((new GsonBuilder()).registerTypeAdapter(TimeZone.class, new CompatibleTimeZoneTypeAdapter()).registerTypeAdapter(Cipher.class, new CipherTypeAdapter()).addSerializationExclusionStrategy(new SerializeExclusionStragtegy()).setDateFormat(FULL_FORMAT)).create(); + gsonCloner = Converters.registerDateTime((new GsonBuilder()).registerTypeAdapter(TimeZone.class, new CompatibleTimeZoneTypeAdapter()).registerTypeAdapter(Cipher.class, new CipherTypeAdapter()).setDateFormat(FULL_FORMAT)).create(); + } + + private static class SerializeExclusionStragtegy implements ExclusionStrategy { + public boolean shouldSkipField(FieldAttributes f) { + Expose expose = (Expose)f.getAnnotation(Expose.class); + return expose != null && !expose.serialize(); + } + + public boolean shouldSkipClass(Class clazz) { + return false; + } + } +} diff --git a/src/main/java/com/mitac/cell/utils/McNumberUtils.java b/src/main/java/com/mitac/cell/utils/McNumberUtils.java new file mode 100644 index 0000000..0356053 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McNumberUtils.java @@ -0,0 +1,69 @@ +package com.mitac.cell.utils; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.Locale; + +public class McNumberUtils { + public static Integer toInt(Object number) { + return toInt(number, (Integer)null); + } + + public static Integer toInt(Object number, Integer defaultValue) { + Number value = toNumber(number); + return value == null ? defaultValue : value.intValue(); + } + + public static int toInt(boolean isLittleEndian, byte[] value) { + return ByteBuffer.wrap(value).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).getInt(); + } + + public static Long toLong(Object number) { + return toLong(number, (Long)null); + } + + public static Long toLong(Object number, Long defaultValue) { + Number value = toNumber(number); + return value == null ? defaultValue : value.longValue(); + } + + public static Float toFloat(Object number) { + return toFloat(number, (Float)null); + } + + public static Float toFloat(Object number, Float defaultValue) { + Number value = toNumber(number); + return value == null ? defaultValue : value.floatValue(); + } + + public static Double toDouble(Object number) { + return toNumber(number).doubleValue(); + } + + public static Double toDouble(Object number, Double defaultValue) { + Number value = toNumber(number); + return value == null ? defaultValue : value.doubleValue(); + } + + public static Number toNumber(Object number) { + if (number == null) { + return null; + } else if (number instanceof Number) { + return (Number)number; + } else if (number instanceof String) { + try { + return NumberFormat.getNumberInstance(Locale.getDefault()).parse((String)number); + } catch (ParseException var2) { + return null; + } + } else { + return null; + } + } + + public static byte[] toBytes(int size, boolean isLittleEndian, int value) { + return ByteBuffer.allocate(size).order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).putInt(value).array(); + } +} diff --git a/src/main/java/com/mitac/cell/utils/McStringUtils.java b/src/main/java/com/mitac/cell/utils/McStringUtils.java new file mode 100644 index 0000000..fe75796 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McStringUtils.java @@ -0,0 +1,212 @@ +package com.mitac.cell.utils; + +import com.google.common.base.CharMatcher; +import com.google.common.base.Strings; +import com.google.common.io.BaseEncoding; +import com.mitac.cell.security.McTextEncryptor; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.regex.Pattern; + +public class McStringUtils { + static final String PRINTABLE_ASCII = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + + public static boolean isValid(String text) { + return !isNullOrEmpty(text, true); + } + + public static boolean isNullOrEmpty(String text) { + return isNullOrEmpty(text, true); + } + + public static boolean isNullOrEmpty(String text, boolean trimAllWhiteSpace) { + if (Strings.isNullOrEmpty(text)) { + return true; + } else { + if (trimAllWhiteSpace) { + text = CharMatcher.whitespace().removeFrom(text); + } + + return Strings.isNullOrEmpty(text); + } + } + + public static String trim(String text, char trimBy) { + return CharMatcher.is(trimBy).trimFrom(text); + } + + public static List convertToIntList(String csvString) { + if (csvString == null) { + return null; + } else { + List list = new ArrayList(); + int i = 0; + int a = 0; + + for(int n = csvString.length(); i < n; ++i) { + switch (csvString.charAt(i)) { + case ' ': + break; + case '!': + case '"': + case '#': + case '$': + case '%': + case '&': + case '\'': + case '(': + case ')': + case '*': + case '+': + case '-': + case '.': + case '/': + default: + throw new AssertionError(); + case ',': + list.add(a); + a = 0; + break; + case '0': + a *= 10; + break; + case '1': + a = a * 10 + 1; + break; + case '2': + a = a * 10 + 2; + break; + case '3': + a = a * 10 + 3; + break; + case '4': + a = a * 10 + 4; + break; + case '5': + a = a * 10 + 5; + break; + case '6': + a = a * 10 + 6; + break; + case '7': + a = a * 10 + 7; + break; + case '8': + a = a * 10 + 8; + break; + case '9': + a = a * 10 + 9; + } + } + + return list; + } + } + + public static String toHexString(byte[] bytes) { + return bytes == null ? null : BaseEncoding.base16().lowerCase().encode(bytes); + } + + public static String toHexStringWithSeparator(byte[] bytes, String separator) { + return BaseEncoding.base16().withSeparator(separator, 2).encode(bytes); + } + + public static byte[] toBytes(String hexString) { + return isNullOrEmpty(hexString) ? null : BaseEncoding.base16().lowerCase().decode(hexString); + } + + public static String toEncryptedBytes(String tokenPassword, String tokenSalt, byte[] source) { + return (new McTextEncryptor(tokenPassword, tokenSalt)).encrypt(toHexString(source)); + } + + public static byte[] toDecryptedBytes(String tokenPassword, String tokenSalt, String source) { + String hexString = (new McTextEncryptor(tokenPassword, tokenSalt)).decrypt(source); + return toBytes(hexString); + } + + public static String toEncrypted(String tokenPassword, String tokenSalt, String source) { + return (new McTextEncryptor(tokenPassword, tokenSalt)).encrypt(source); + } + + public static String toDecrypted(String tokenPassword, String tokenSalt, String source) { + return (new McTextEncryptor(tokenPassword, tokenSalt)).decrypt(source); + } + + public static String random(int length) { + if (length < 0) { + return null; + } else if (length == 0) { + return ""; + } else { + int gap = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".length(); + Random random = new Random(); + StringBuilder sb = new StringBuilder(); + + while(length-- != 0) { + sb.append("!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".charAt(random.nextInt(gap))); + } + + return sb.toString(); + } + } + + public static String randomNumeric(int length) { + if (length < 0) { + return null; + } else if (length == 0) { + return ""; + } else { + Random random = new Random(); + StringBuilder sb = new StringBuilder(); + + while(length-- != 0) { + sb.append(random.nextInt(10)); + } + + return sb.toString(); + } + } + + public static String toBase64(byte[] bytes) { + return bytes != null && bytes.length != 0 ? BaseEncoding.base64().omitPadding().encode(bytes) : null; + } + + public static byte[] fromBase64(String base64String) { + return Strings.isNullOrEmpty(base64String) ? null : BaseEncoding.base64().omitPadding().decode(base64String); + } + + public static boolean containsIgnoreCase(String source, String what) { + if (!Strings.isNullOrEmpty(source) && !Strings.isNullOrEmpty(what)) { + int len = what.length(); + int max = source.length() - len; + + while(max >= 0) { + if (source.regionMatches(true, max--, what, 0, len)) { + return true; + } + } + + return false; + } else { + return false; + } + } + + public static boolean hasUpperLowerDigit(String text) { + Pattern textPattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).+$"); + return textPattern.matcher(text).matches(); + } + + public static String stackTrace(Exception ex) { + if (ex == null) { + return ""; + } else { + StringWriter stringWriter = new StringWriter(); + ex.printStackTrace(new PrintWriter(stringWriter)); + return stringWriter.toString(); + } + } +} diff --git a/src/main/java/com/mitac/cell/utils/McUrlUtils.java b/src/main/java/com/mitac/cell/utils/McUrlUtils.java new file mode 100644 index 0000000..048badb --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McUrlUtils.java @@ -0,0 +1,45 @@ +package com.mitac.cell.utils; + +import com.google.common.net.UrlEscapers; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import javax.servlet.http.HttpServletRequest; + +public class McUrlUtils { + public static String getHostUrl(HttpServletRequest request) { + String hostUrl = request.getRequestURL().toString(); + hostUrl = hostUrl.substring(0, hostUrl.indexOf(request.getRequestURI())); + String contextPath = request.getContextPath(); + if (!McStringUtils.isNullOrEmpty(contextPath)) { + hostUrl = hostUrl + contextPath; + } + + return hostUrl; + } + + public static String getPropertyKey(String key) { + if (key.contains(".")) { + return key.substring(key.indexOf(".") + 1); + } else if (key.contains("[")) { + int start = key.indexOf(39) + 1; + int last = key.lastIndexOf(39); + return key.substring(start, last).trim(); + } else { + return null; + } + } + + public static String encode(String name) { + name = UrlEscapers.urlPathSegmentEscaper().escape(name); + return URLEncoder.encode(name, Charset.defaultCharset()); + } + + public static URL toUrl(String url) { + try { + return new URL(url); + } catch (Exception var2) { + return null; + } + } +} diff --git a/src/main/java/com/mitac/cell/utils/McUuidUtils.java b/src/main/java/com/mitac/cell/utils/McUuidUtils.java new file mode 100644 index 0000000..d239dc0 --- /dev/null +++ b/src/main/java/com/mitac/cell/utils/McUuidUtils.java @@ -0,0 +1,90 @@ +package com.mitac.cell.utils; + +import com.google.common.base.Strings; +import com.google.common.io.BaseEncoding; +import com.mitac.cell.security.McTextEncryptor; +import java.nio.ByteBuffer; +import java.util.UUID; +import javax.xml.bind.DatatypeConverter; + +public class McUuidUtils { + private static final String tokenPassword = "MiDM@MiTAC.com"; + private static final String tokenSalt = "171891893b5cef2f"; + public static final McTextEncryptor encryptor = new McTextEncryptor("MiDM@MiTAC.com", "171891893b5cef2f"); + + public static byte[] toBytes(UUID uuid) { + long hi = uuid.getMostSignificantBits(); + long lo = uuid.getLeastSignificantBits(); + return ByteBuffer.allocate(16).putLong(hi).putLong(lo).array(); + } + + public static String toHexString(UUID uuid) { + return uuid.toString().replace("-", ""); + } + + public static byte[] toOrderedBytes(UUID uuid) { + String hexValue = uuid.toString().replace("-", ""); + return DatatypeConverter.parseHexBinary(hexValue); + } + + public static UUID fromString(String hexValue) { + byte[] byteUuid = DatatypeConverter.parseHexBinary(hexValue.replace("-", "")); + String formattedValue = toStringFromOrderedBytes(byteUuid); + return UUID.fromString(formattedValue); + } + + public static UUID fromOrderedBytes(byte[] idValue) { + return UUID.fromString(toStringFromOrderedBytes(idValue)); + } + + public static String toStringFromOrderedBytes(byte[] idValue) { + StringBuilder sb = new StringBuilder(); + + for(int i = 0; i < 16; ++i) { + byte byteValue = i < idValue.length ? idValue[i] : 0; + sb.append(String.format("%02x", byteValue)); + if (i == 3 || i == 5 || i == 7 || i == 9) { + sb.append('-'); + } + } + + return sb.toString(); + } + + public static String toBase64String(UUID uuid) { + return toBase64String(uuid, false); + } + + public static String toBase64String(UUID uuid, boolean omitPadding) { + BaseEncoding encoding = BaseEncoding.base64Url(); + if (omitPadding) { + encoding = encoding.omitPadding(); + } + + return encoding.encode(toOrderedBytes(uuid)); + } + + public static UUID toUuidFromBase64(String token) { + try { + return Strings.isNullOrEmpty(token) ? null : UUID.fromString(toStringFromOrderedBytes(BaseEncoding.base64Url().decode(token))); + } catch (Exception var2) { + return null; + } + } + + public static String encrypt(UUID uuid) { + try { + return encryptor.encrypt(toHexString(uuid)); + } catch (Exception var2) { + return null; + } + } + + public static UUID decrypt(String encryptedUuid) { + try { + return fromString(encryptor.decrypt(encryptedUuid)); + } catch (Exception var2) { + return null; + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/ClassPathIndexFile.java b/src/main/java/org/springframework/boot/loader/ClassPathIndexFile.java new file mode 100644 index 0000000..2e991b4 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/ClassPathIndexFile.java @@ -0,0 +1,119 @@ +package org.springframework.boot.loader; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +final class ClassPathIndexFile { + private final File root; + private final List lines; + + private ClassPathIndexFile(File root, List lines) { + this.root = root; + this.lines = (List)lines.stream().map(this::extractName).collect(Collectors.toList()); + } + + private String extractName(String line) { + if (line.startsWith("- \"") && line.endsWith("\"")) { + return line.substring(3, line.length() - 1); + } else { + throw new IllegalStateException("Malformed classpath index line [" + line + "]"); + } + } + + int size() { + return this.lines.size(); + } + + boolean containsEntry(String name) { + return name != null && !name.isEmpty() ? this.lines.contains(name) : false; + } + + List getUrls() { + return Collections.unmodifiableList((List)this.lines.stream().map(this::asUrl).collect(Collectors.toList())); + } + + private URL asUrl(String line) { + try { + return (new File(this.root, line)).toURI().toURL(); + } catch (MalformedURLException ex) { + throw new IllegalStateException(ex); + } + } + + static ClassPathIndexFile loadIfPossible(URL root, String location) throws IOException { + return loadIfPossible(asFile(root), location); + } + + private static ClassPathIndexFile loadIfPossible(File root, String location) throws IOException { + return loadIfPossible(root, new File(root, location)); + } + + private static ClassPathIndexFile loadIfPossible(File root, File indexFile) throws IOException { + if (indexFile.exists() && indexFile.isFile()) { + InputStream inputStream = new FileInputStream(indexFile); + Throwable var3 = null; + + ClassPathIndexFile var4; + try { + var4 = new ClassPathIndexFile(root, loadLines(inputStream)); + } catch (Throwable var13) { + var3 = var13; + throw var13; + } finally { + if (inputStream != null) { + if (var3 != null) { + try { + inputStream.close(); + } catch (Throwable var12) { + var3.addSuppressed(var12); + } + } else { + inputStream.close(); + } + } + + } + + return var4; + } else { + return null; + } + } + + private static List loadLines(InputStream inputStream) throws IOException { + List lines = new ArrayList(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); + + for(String line = reader.readLine(); line != null; line = reader.readLine()) { + if (!line.trim().isEmpty()) { + lines.add(line); + } + } + + return Collections.unmodifiableList(lines); + } + + private static File asFile(URL url) { + if (!"file".equals(url.getProtocol())) { + throw new IllegalArgumentException("URL does not reference a file"); + } else { + try { + return new File(url.toURI()); + } catch (URISyntaxException var2) { + return new File(url.getPath()); + } + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java b/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java new file mode 100644 index 0000000..fba9a68 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java @@ -0,0 +1,135 @@ +package org.springframework.boot.loader; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import org.springframework.boot.loader.archive.Archive; +import org.springframework.boot.loader.archive.ExplodedArchive; + +public abstract class ExecutableArchiveLauncher extends Launcher { + private static final String START_CLASS_ATTRIBUTE = "Start-Class"; + protected static final String BOOT_CLASSPATH_INDEX_ATTRIBUTE = "Spring-Boot-Classpath-Index"; + protected static final String DEFAULT_CLASSPATH_INDEX_FILE_NAME = "classpath.idx"; + private final Archive archive; + private final ClassPathIndexFile classPathIndex; + + public ExecutableArchiveLauncher() { + try { + this.archive = this.createArchive(); + this.classPathIndex = this.getClassPathIndex(this.archive); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + protected ExecutableArchiveLauncher(Archive archive) { + try { + this.archive = archive; + this.classPathIndex = this.getClassPathIndex(this.archive); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + protected ClassPathIndexFile getClassPathIndex(Archive archive) throws IOException { + if (archive instanceof ExplodedArchive) { + String location = this.getClassPathIndexFileLocation(archive); + return ClassPathIndexFile.loadIfPossible(archive.getUrl(), location); + } else { + return null; + } + } + + private String getClassPathIndexFileLocation(Archive archive) throws IOException { + Manifest manifest = archive.getManifest(); + Attributes attributes = manifest != null ? manifest.getMainAttributes() : null; + String location = attributes != null ? attributes.getValue("Spring-Boot-Classpath-Index") : null; + return location != null ? location : this.getArchiveEntryPathPrefix() + "classpath.idx"; + } + + protected String getMainClass() throws Exception { + Manifest manifest = this.archive.getManifest(); + String mainClass = null; + if (manifest != null) { + mainClass = manifest.getMainAttributes().getValue("Start-Class"); + } + + if (mainClass == null) { + throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this); + } else { + return mainClass; + } + } + + protected ClassLoader createClassLoader(Iterator archives) throws Exception { + List urls = new ArrayList(this.guessClassPathSize()); + + while(archives.hasNext()) { + urls.add(((Archive)archives.next()).getUrl()); + } + + if (this.classPathIndex != null) { + urls.addAll(this.classPathIndex.getUrls()); + } + + return this.createClassLoader((URL[])urls.toArray(new URL[0])); + } + + private int guessClassPathSize() { + return this.classPathIndex != null ? this.classPathIndex.size() + 10 : 50; + } + + protected Iterator getClassPathArchivesIterator() throws Exception { + Archive.EntryFilter searchFilter = this::isSearchCandidate; + Iterator archives = this.archive.getNestedArchives(searchFilter, (entry) -> this.isNestedArchive(entry) && !this.isEntryIndexed(entry)); + if (this.isPostProcessingClassPathArchives()) { + archives = this.applyClassPathArchivePostProcessing(archives); + } + + return archives; + } + + private boolean isEntryIndexed(Archive.Entry entry) { + return this.classPathIndex != null ? this.classPathIndex.containsEntry(entry.getName()) : false; + } + + private Iterator applyClassPathArchivePostProcessing(Iterator archives) throws Exception { + List list = new ArrayList(); + + while(archives.hasNext()) { + list.add(archives.next()); + } + + this.postProcessClassPathArchives(list); + return list.iterator(); + } + + protected boolean isSearchCandidate(Archive.Entry entry) { + return this.getArchiveEntryPathPrefix() == null ? true : entry.getName().startsWith(this.getArchiveEntryPathPrefix()); + } + + protected abstract boolean isNestedArchive(Archive.Entry entry); + + protected boolean isPostProcessingClassPathArchives() { + return true; + } + + protected void postProcessClassPathArchives(List archives) throws Exception { + } + + protected String getArchiveEntryPathPrefix() { + return null; + } + + protected boolean isExploded() { + return this.archive.isExploded(); + } + + protected final Archive getArchive() { + return this.archive; + } +} diff --git a/src/main/java/org/springframework/boot/loader/JarLauncher.java b/src/main/java/org/springframework/boot/loader/JarLauncher.java new file mode 100644 index 0000000..ea4edd4 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/JarLauncher.java @@ -0,0 +1,30 @@ +package org.springframework.boot.loader; + +import org.springframework.boot.loader.archive.Archive; + +public class JarLauncher extends ExecutableArchiveLauncher { + static final Archive.EntryFilter NESTED_ARCHIVE_ENTRY_FILTER = (entry) -> entry.isDirectory() ? entry.getName().equals("BOOT-INF/classes/") : entry.getName().startsWith("BOOT-INF/lib/"); + + public JarLauncher() { + } + + protected JarLauncher(Archive archive) { + super(archive); + } + + protected boolean isPostProcessingClassPathArchives() { + return false; + } + + protected boolean isNestedArchive(Archive.Entry entry) { + return NESTED_ARCHIVE_ENTRY_FILTER.matches(entry); + } + + protected String getArchiveEntryPathPrefix() { + return "BOOT-INF/"; + } + + public static void main(String[] args) throws Exception { + (new JarLauncher()).launch(args); + } +} diff --git a/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java b/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java new file mode 100644 index 0000000..bc84b56 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java @@ -0,0 +1,303 @@ +package org.springframework.boot.loader; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.JarURLConnection; +import java.net.URL; +import java.net.URLClassLoader; +import java.net.URLConnection; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.util.Enumeration; +import java.util.function.Supplier; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import org.springframework.boot.loader.archive.Archive; +import org.springframework.boot.loader.jar.Handler; + +public class LaunchedURLClassLoader extends URLClassLoader { + private static final int BUFFER_SIZE = 4096; + private final boolean exploded; + private final Archive rootArchive; + private final Object packageLock; + private volatile DefinePackageCallType definePackageCallType; + + public LaunchedURLClassLoader(URL[] urls, ClassLoader parent) { + this(false, urls, parent); + } + + public LaunchedURLClassLoader(boolean exploded, URL[] urls, ClassLoader parent) { + this(exploded, (Archive)null, urls, parent); + } + + public LaunchedURLClassLoader(boolean exploded, Archive rootArchive, URL[] urls, ClassLoader parent) { + super(urls, parent); + this.packageLock = new Object(); + this.exploded = exploded; + this.rootArchive = rootArchive; + } + + public URL findResource(String name) { + if (this.exploded) { + return super.findResource(name); + } else { + Handler.setUseFastConnectionExceptions(true); + + URL var2; + try { + var2 = super.findResource(name); + } finally { + Handler.setUseFastConnectionExceptions(false); + } + + return var2; + } + } + + public Enumeration findResources(String name) throws IOException { + if (this.exploded) { + return super.findResources(name); + } else { + Handler.setUseFastConnectionExceptions(true); + + UseFastConnectionExceptionsEnumeration var2; + try { + var2 = new UseFastConnectionExceptionsEnumeration(super.findResources(name)); + } finally { + Handler.setUseFastConnectionExceptions(false); + } + + return var2; + } + } + + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (name.startsWith("org.springframework.boot.loader.jarmode.")) { + try { + Class result = this.loadClassInLaunchedClassLoader(name); + if (resolve) { + this.resolveClass(result); + } + + return result; + } catch (ClassNotFoundException var10) { + } + } + + if (this.exploded) { + return super.loadClass(name, resolve); + } else { + Handler.setUseFastConnectionExceptions(true); + + Class result; + try { + try { + this.definePackageIfNecessary(name); + } catch (IllegalArgumentException var8) { + if (this.getPackage(name) == null) { + throw new AssertionError("Package " + name + " has already been defined but it could not be found"); + } + } + + result = super.loadClass(name, resolve); + } finally { + Handler.setUseFastConnectionExceptions(false); + } + + return result; + } + } + + private Class loadClassInLaunchedClassLoader(String name) throws ClassNotFoundException { + String internalName = name.replace('.', '/') + ".class"; + InputStream inputStream = this.getParent().getResourceAsStream(internalName); + if (inputStream == null) { + throw new ClassNotFoundException(name); + } else { + try { + Class var9; + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int bytesRead = -1; + + while((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + + inputStream.close(); + byte[] bytes = outputStream.toByteArray(); + Class definedClass = this.defineClass(name, bytes, 0, bytes.length); + this.definePackageIfNecessary(name); + var9 = definedClass; + } finally { + inputStream.close(); + } + + return var9; + } catch (IOException ex) { + throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex); + } + } + } + + private void definePackageIfNecessary(String className) { + int lastDot = className.lastIndexOf(46); + if (lastDot >= 0) { + String packageName = className.substring(0, lastDot); + if (this.getPackage(packageName) == null) { + try { + this.definePackage(className, packageName); + } catch (IllegalArgumentException var5) { + if (this.getPackage(packageName) == null) { + throw new AssertionError("Package " + packageName + " has already been defined but it could not be found"); + } + } + } + } + + } + + private void definePackage(String className, String packageName) { + try { + AccessController.doPrivileged(() -> { + String packageEntryName = packageName.replace('.', '/') + "/"; + String classEntryName = className.replace('.', '/') + ".class"; + + for(URL url : this.getURLs()) { + try { + URLConnection connection = url.openConnection(); + if (connection instanceof JarURLConnection) { + JarFile jarFile = ((JarURLConnection)connection).getJarFile(); + if (jarFile.getEntry(classEntryName) != null && jarFile.getEntry(packageEntryName) != null && jarFile.getManifest() != null) { + this.definePackage(packageName, jarFile.getManifest(), url); + return null; + } + } + } catch (IOException var11) { + } + } + + return null; + }, AccessController.getContext()); + } catch (PrivilegedActionException var4) { + } + + } + + protected Package definePackage(String name, Manifest man, URL url) throws IllegalArgumentException { + if (!this.exploded) { + return super.definePackage(name, man, url); + } else { + synchronized(this.packageLock) { + return (Package)this.doDefinePackage(LaunchedURLClassLoader.DefinePackageCallType.MANIFEST, () -> super.definePackage(name, man, url)); + } + } + } + + protected Package definePackage(String name, String specTitle, String specVersion, String specVendor, String implTitle, String implVersion, String implVendor, URL sealBase) throws IllegalArgumentException { + if (!this.exploded) { + return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase); + } else { + synchronized(this.packageLock) { + if (this.definePackageCallType == null) { + Manifest manifest = this.getManifest(this.rootArchive); + if (manifest != null) { + return this.definePackage(name, manifest, sealBase); + } + } + + return (Package)this.doDefinePackage(LaunchedURLClassLoader.DefinePackageCallType.ATTRIBUTES, () -> super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase)); + } + } + } + + private Manifest getManifest(Archive archive) { + try { + return archive != null ? archive.getManifest() : null; + } catch (IOException var3) { + return null; + } + } + + private Object doDefinePackage(DefinePackageCallType type, Supplier call) { + DefinePackageCallType existingType = this.definePackageCallType; + + Object var4; + try { + this.definePackageCallType = type; + var4 = call.get(); + } finally { + this.definePackageCallType = existingType; + } + + return var4; + } + + public void clearCache() { + if (!this.exploded) { + for(URL url : this.getURLs()) { + try { + URLConnection connection = url.openConnection(); + if (connection instanceof JarURLConnection) { + this.clearCache(connection); + } + } catch (IOException var6) { + } + } + + } + } + + private void clearCache(URLConnection connection) throws IOException { + Object jarFile = ((JarURLConnection)connection).getJarFile(); + if (jarFile instanceof org.springframework.boot.loader.jar.JarFile) { + ((org.springframework.boot.loader.jar.JarFile)jarFile).clearCache(); + } + + } + + static { + ClassLoader.registerAsParallelCapable(); + } + + private static class UseFastConnectionExceptionsEnumeration implements Enumeration { + private final Enumeration delegate; + + UseFastConnectionExceptionsEnumeration(Enumeration delegate) { + this.delegate = delegate; + } + + public boolean hasMoreElements() { + Handler.setUseFastConnectionExceptions(true); + + boolean var1; + try { + var1 = this.delegate.hasMoreElements(); + } finally { + Handler.setUseFastConnectionExceptions(false); + } + + return var1; + } + + public URL nextElement() { + Handler.setUseFastConnectionExceptions(true); + + URL var1; + try { + var1 = (URL)this.delegate.nextElement(); + } finally { + Handler.setUseFastConnectionExceptions(false); + } + + return var1; + } + } + + private static enum DefinePackageCallType { + MANIFEST, + ATTRIBUTES; + } +} diff --git a/src/main/java/org/springframework/boot/loader/Launcher.java b/src/main/java/org/springframework/boot/loader/Launcher.java new file mode 100644 index 0000000..c8591d2 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/Launcher.java @@ -0,0 +1,95 @@ +package org.springframework.boot.loader; + +import java.io.File; +import java.net.URI; +import java.net.URL; +import java.security.CodeSource; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.springframework.boot.loader.archive.Archive; +import org.springframework.boot.loader.archive.ExplodedArchive; +import org.springframework.boot.loader.archive.JarFileArchive; +import org.springframework.boot.loader.jar.JarFile; + +public abstract class Launcher { + private static final String JAR_MODE_LAUNCHER = "org.springframework.boot.loader.jarmode.JarModeLauncher"; + + protected void launch(String[] args) throws Exception { + if (!this.isExploded()) { + JarFile.registerUrlProtocolHandler(); + } + + ClassLoader classLoader = this.createClassLoader(this.getClassPathArchivesIterator()); + String jarMode = System.getProperty("jarmode"); + String launchClass = jarMode != null && !jarMode.isEmpty() ? "org.springframework.boot.loader.jarmode.JarModeLauncher" : this.getMainClass(); + this.launch(args, launchClass, classLoader); + } + + /** @deprecated */ + @Deprecated + protected ClassLoader createClassLoader(List archives) throws Exception { + return this.createClassLoader(archives.iterator()); + } + + protected ClassLoader createClassLoader(Iterator archives) throws Exception { + List urls = new ArrayList(50); + + while(archives.hasNext()) { + urls.add(((Archive)archives.next()).getUrl()); + } + + return this.createClassLoader((URL[])urls.toArray(new URL[0])); + } + + protected ClassLoader createClassLoader(URL[] urls) throws Exception { + return new LaunchedURLClassLoader(this.isExploded(), this.getArchive(), urls, this.getClass().getClassLoader()); + } + + protected void launch(String[] args, String launchClass, ClassLoader classLoader) throws Exception { + Thread.currentThread().setContextClassLoader(classLoader); + this.createMainMethodRunner(launchClass, args, classLoader).run(); + } + + protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, ClassLoader classLoader) { + return new MainMethodRunner(mainClass, args); + } + + protected abstract String getMainClass() throws Exception; + + protected Iterator getClassPathArchivesIterator() throws Exception { + return this.getClassPathArchives().iterator(); + } + + /** @deprecated */ + @Deprecated + protected List getClassPathArchives() throws Exception { + throw new IllegalStateException("Unexpected call to getClassPathArchives()"); + } + + protected final Archive createArchive() throws Exception { + ProtectionDomain protectionDomain = this.getClass().getProtectionDomain(); + CodeSource codeSource = protectionDomain.getCodeSource(); + URI location = codeSource != null ? codeSource.getLocation().toURI() : null; + String path = location != null ? location.getSchemeSpecificPart() : null; + if (path == null) { + throw new IllegalStateException("Unable to determine code source archive"); + } else { + File root = new File(path); + if (!root.exists()) { + throw new IllegalStateException("Unable to determine code source archive from " + root); + } else { + return (Archive)(root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root)); + } + } + } + + protected boolean isExploded() { + return false; + } + + protected Archive getArchive() { + return null; + } +} diff --git a/src/main/java/org/springframework/boot/loader/MainMethodRunner.java b/src/main/java/org/springframework/boot/loader/MainMethodRunner.java new file mode 100644 index 0000000..596619f --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/MainMethodRunner.java @@ -0,0 +1,21 @@ +package org.springframework.boot.loader; + +import [Ljava.lang.String;; +import java.lang.reflect.Method; + +public class MainMethodRunner { + private final String mainClassName; + private final String[] args; + + public MainMethodRunner(String mainClass, String[] args) { + this.mainClassName = mainClass; + this.args = args != null ? (String[])((String;)args).clone() : null; + } + + public void run() throws Exception { + Class mainClass = Class.forName(this.mainClassName, false, Thread.currentThread().getContextClassLoader()); + Method mainMethod = mainClass.getDeclaredMethod("main", String[].class); + mainMethod.setAccessible(true); + mainMethod.invoke((Object)null, this.args); + } +} diff --git a/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java b/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java new file mode 100644 index 0000000..95cd404 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java @@ -0,0 +1,658 @@ +package org.springframework.boot.loader; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Constructor; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.jar.Manifest; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.springframework.boot.loader.archive.Archive; +import org.springframework.boot.loader.archive.ExplodedArchive; +import org.springframework.boot.loader.archive.JarFileArchive; +import org.springframework.boot.loader.util.SystemPropertyUtils; + +public class PropertiesLauncher extends Launcher { + private static final Class[] PARENT_ONLY_PARAMS = new Class[]{ClassLoader.class}; + private static final Class[] URLS_AND_PARENT_PARAMS = new Class[]{URL[].class, ClassLoader.class}; + private static final Class[] NO_PARAMS = new Class[0]; + private static final URL[] NO_URLS = new URL[0]; + private static final String DEBUG = "loader.debug"; + public static final String MAIN = "loader.main"; + public static final String PATH = "loader.path"; + public static final String HOME = "loader.home"; + public static final String ARGS = "loader.args"; + public static final String CONFIG_NAME = "loader.config.name"; + public static final String CONFIG_LOCATION = "loader.config.location"; + public static final String SET_SYSTEM_PROPERTIES = "loader.system"; + private static final Pattern WORD_SEPARATOR = Pattern.compile("\\W+"); + private static final String NESTED_ARCHIVE_SEPARATOR; + private final File home; + private List paths = new ArrayList(); + private final Properties properties = new Properties(); + private final Archive parent; + private volatile ClassPathArchives classPathArchives; + + public PropertiesLauncher() { + try { + this.home = this.getHomeDirectory(); + this.initializeProperties(); + this.initializePaths(); + this.parent = this.createArchive(); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + protected File getHomeDirectory() { + try { + return new File(this.getPropertyWithDefault("loader.home", "${user.dir}")); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private void initializeProperties() throws Exception { + List configs = new ArrayList(); + if (this.getProperty("loader.config.location") != null) { + configs.add(this.getProperty("loader.config.location")); + } else { + String[] names = this.getPropertyWithDefault("loader.config.name", "loader").split(","); + + for(String name : names) { + configs.add("file:" + this.getHomeDirectory() + "/" + name + ".properties"); + configs.add("classpath:" + name + ".properties"); + configs.add("classpath:BOOT-INF/classes/" + name + ".properties"); + } + } + + Iterator var17 = configs.iterator(); + + while(true) { + if (var17.hasNext()) { + String config = (String)var17.next(); + InputStream resource = this.getResource(config); + Throwable var20 = null; + + try { + if (resource == null) { + this.debug("Not found: " + config); + continue; + } + + this.debug("Found: " + config); + this.loadResource(resource); + } catch (Throwable var15) { + var20 = var15; + throw var15; + } finally { + if (resource != null) { + if (var20 != null) { + try { + resource.close(); + } catch (Throwable var14) { + var20.addSuppressed(var14); + } + } else { + resource.close(); + } + } + + } + + return; + } + + return; + } + } + + private void loadResource(InputStream resource) throws Exception { + this.properties.load(resource); + + for(Object key : Collections.list(this.properties.propertyNames())) { + String text = this.properties.getProperty((String)key); + String value = SystemPropertyUtils.resolvePlaceholders(this.properties, text); + if (value != null) { + this.properties.put(key, value); + } + } + + if ("true".equals(this.getProperty("loader.system"))) { + this.debug("Adding resolved properties to System properties"); + + for(Object key : Collections.list(this.properties.propertyNames())) { + String value = this.properties.getProperty((String)key); + System.setProperty((String)key, value); + } + } + + } + + private InputStream getResource(String config) throws Exception { + if (config.startsWith("classpath:")) { + return this.getClasspathResource(config.substring("classpath:".length())); + } else { + config = this.handleUrl(config); + return this.isUrl(config) ? this.getURLResource(config) : this.getFileResource(config); + } + } + + private String handleUrl(String path) throws UnsupportedEncodingException { + if (path.startsWith("jar:file:") || path.startsWith("file:")) { + path = URLDecoder.decode(path, "UTF-8"); + if (path.startsWith("file:")) { + path = path.substring("file:".length()); + if (path.startsWith("//")) { + path = path.substring(2); + } + } + } + + return path; + } + + private boolean isUrl(String config) { + return config.contains("://"); + } + + private InputStream getClasspathResource(String config) { + while(config.startsWith("/")) { + config = config.substring(1); + } + + config = "/" + config; + this.debug("Trying classpath: " + config); + return this.getClass().getResourceAsStream(config); + } + + private InputStream getFileResource(String config) throws Exception { + File file = new File(config); + this.debug("Trying file: " + config); + return file.canRead() ? new FileInputStream(file) : null; + } + + private InputStream getURLResource(String config) throws Exception { + URL url = new URL(config); + if (this.exists(url)) { + URLConnection con = url.openConnection(); + + try { + return con.getInputStream(); + } catch (IOException ex) { + if (con instanceof HttpURLConnection) { + ((HttpURLConnection)con).disconnect(); + } + + throw ex; + } + } else { + return null; + } + } + + private boolean exists(URL url) throws IOException { + URLConnection connection = url.openConnection(); + + try { + connection.setUseCaches(connection.getClass().getSimpleName().startsWith("JNLP")); + if (connection instanceof HttpURLConnection) { + HttpURLConnection httpConnection = (HttpURLConnection)connection; + httpConnection.setRequestMethod("HEAD"); + int responseCode = httpConnection.getResponseCode(); + if (responseCode == 200) { + boolean var10 = true; + return var10; + } + + if (responseCode == 404) { + boolean var5 = false; + return var5; + } + } + + boolean var9 = connection.getContentLength() >= 0; + return var9; + } finally { + if (connection instanceof HttpURLConnection) { + ((HttpURLConnection)connection).disconnect(); + } + + } + } + + private void initializePaths() throws Exception { + String path = this.getProperty("loader.path"); + if (path != null) { + this.paths = this.parsePathsProperty(path); + } + + this.debug("Nested archive paths: " + this.paths); + } + + private List parsePathsProperty(String commaSeparatedPaths) { + List paths = new ArrayList(); + + for(String path : commaSeparatedPaths.split(",")) { + path = this.cleanupPath(path); + path = path != null && !path.isEmpty() ? path : "/"; + paths.add(path); + } + + if (paths.isEmpty()) { + paths.add("lib"); + } + + return paths; + } + + protected String[] getArgs(String... args) throws Exception { + String loaderArgs = this.getProperty("loader.args"); + if (loaderArgs != null) { + String[] defaultArgs = loaderArgs.split("\\s+"); + String[] additionalArgs = args; + args = new String[defaultArgs.length + args.length]; + System.arraycopy(defaultArgs, 0, args, 0, defaultArgs.length); + System.arraycopy(additionalArgs, 0, args, defaultArgs.length, additionalArgs.length); + } + + return args; + } + + protected String getMainClass() throws Exception { + String mainClass = this.getProperty("loader.main", "Start-Class"); + if (mainClass == null) { + throw new IllegalStateException("No 'loader.main' or 'Start-Class' specified"); + } else { + return mainClass; + } + } + + protected ClassLoader createClassLoader(Iterator archives) throws Exception { + String customLoaderClassName = this.getProperty("loader.classLoader"); + if (customLoaderClassName == null) { + return super.createClassLoader(archives); + } else { + Set urls = new LinkedHashSet(); + + while(archives.hasNext()) { + urls.add(((Archive)archives.next()).getUrl()); + } + + ClassLoader loader = new LaunchedURLClassLoader((URL[])urls.toArray(NO_URLS), this.getClass().getClassLoader()); + this.debug("Classpath for custom loader: " + urls); + ClassLoader var5 = this.wrapWithCustomClassLoader(loader, customLoaderClassName); + this.debug("Using custom class loader: " + customLoaderClassName); + return var5; + } + } + + private ClassLoader wrapWithCustomClassLoader(ClassLoader parent, String className) throws Exception { + Class type = Class.forName(className, true, parent); + ClassLoader classLoader = this.newClassLoader(type, PARENT_ONLY_PARAMS, parent); + if (classLoader == null) { + classLoader = this.newClassLoader(type, URLS_AND_PARENT_PARAMS, NO_URLS, parent); + } + + if (classLoader == null) { + classLoader = this.newClassLoader(type, NO_PARAMS); + } + + if (classLoader == null) { + throw new IllegalArgumentException("Unable to create class loader for " + className); + } else { + return classLoader; + } + } + + private ClassLoader newClassLoader(Class loaderClass, Class[] parameterTypes, Object... initargs) throws Exception { + try { + Constructor constructor = loaderClass.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + return (ClassLoader)constructor.newInstance(initargs); + } catch (NoSuchMethodException var5) { + return null; + } + } + + private String getProperty(String propertyKey) throws Exception { + return this.getProperty(propertyKey, (String)null, (String)null); + } + + private String getProperty(String propertyKey, String manifestKey) throws Exception { + return this.getProperty(propertyKey, manifestKey, (String)null); + } + + private String getPropertyWithDefault(String propertyKey, String defaultValue) throws Exception { + return this.getProperty(propertyKey, (String)null, defaultValue); + } + + private String getProperty(String propertyKey, String manifestKey, String defaultValue) throws Exception { + if (manifestKey == null) { + manifestKey = propertyKey.replace('.', '-'); + manifestKey = toCamelCase(manifestKey); + } + + String property = SystemPropertyUtils.getProperty(propertyKey); + if (property != null) { + String value = SystemPropertyUtils.resolvePlaceholders(this.properties, property); + this.debug("Property '" + propertyKey + "' from environment: " + value); + return value; + } else if (this.properties.containsKey(propertyKey)) { + String value = SystemPropertyUtils.resolvePlaceholders(this.properties, this.properties.getProperty(propertyKey)); + this.debug("Property '" + propertyKey + "' from properties: " + value); + return value; + } else { + try { + if (this.home != null) { + label164: { + String var9; + try (ExplodedArchive archive = new ExplodedArchive(this.home, false)) { + Manifest manifest = archive.getManifest(); + if (manifest == null) { + break label164; + } + + String value = manifest.getMainAttributes().getValue(manifestKey); + if (value == null) { + break label164; + } + + this.debug("Property '" + manifestKey + "' from home directory manifest: " + value); + var9 = SystemPropertyUtils.resolvePlaceholders(this.properties, value); + } + + return var9; + } + } + } catch (IllegalStateException var22) { + } + + Manifest manifest = this.createArchive().getManifest(); + if (manifest != null) { + String value = manifest.getMainAttributes().getValue(manifestKey); + if (value != null) { + this.debug("Property '" + manifestKey + "' from archive manifest: " + value); + return SystemPropertyUtils.resolvePlaceholders(this.properties, value); + } + } + + return defaultValue != null ? SystemPropertyUtils.resolvePlaceholders(this.properties, defaultValue) : defaultValue; + } + } + + protected Iterator getClassPathArchivesIterator() throws Exception { + ClassPathArchives classPathArchives = this.classPathArchives; + if (classPathArchives == null) { + classPathArchives = new ClassPathArchives(); + this.classPathArchives = classPathArchives; + } + + return classPathArchives.iterator(); + } + + public static void main(String[] args) throws Exception { + PropertiesLauncher launcher = new PropertiesLauncher(); + args = launcher.getArgs(args); + launcher.launch(args); + } + + public static String toCamelCase(CharSequence string) { + if (string == null) { + return null; + } else { + StringBuilder builder = new StringBuilder(); + Matcher matcher = WORD_SEPARATOR.matcher(string); + + int pos; + for(pos = 0; matcher.find(); pos = matcher.end()) { + builder.append(capitalize(string.subSequence(pos, matcher.end()).toString())); + } + + builder.append(capitalize(string.subSequence(pos, string.length()).toString())); + return builder.toString(); + } + } + + private static String capitalize(String str) { + return Character.toUpperCase(str.charAt(0)) + str.substring(1); + } + + private void debug(String message) { + if (Boolean.getBoolean("loader.debug")) { + System.out.println(message); + } + + } + + private String cleanupPath(String path) { + path = path.trim(); + if (path.startsWith("./")) { + path = path.substring(2); + } + + String lowerCasePath = path.toLowerCase(Locale.ENGLISH); + if (!lowerCasePath.endsWith(".jar") && !lowerCasePath.endsWith(".zip")) { + if (path.endsWith("/*")) { + path = path.substring(0, path.length() - 1); + } else if (!path.endsWith("/") && !path.equals(".")) { + path = path + "/"; + } + + return path; + } else { + return path; + } + } + + void close() throws Exception { + if (this.classPathArchives != null) { + this.classPathArchives.close(); + } + + if (this.parent != null) { + this.parent.close(); + } + + } + + static { + NESTED_ARCHIVE_SEPARATOR = "!" + File.separator; + } + + private class ClassPathArchives implements Iterable { + private final List classPathArchives = new ArrayList(); + private final List jarFileArchives = new ArrayList(); + + ClassPathArchives() throws Exception { + for(String path : PropertiesLauncher.this.paths) { + for(Archive archive : this.getClassPathArchives(path)) { + this.addClassPathArchive(archive); + } + } + + this.addNestedEntries(); + } + + private void addClassPathArchive(Archive archive) throws IOException { + if (!(archive instanceof ExplodedArchive)) { + this.classPathArchives.add(archive); + } else { + this.classPathArchives.add(archive); + this.classPathArchives.addAll(this.asList(archive.getNestedArchives((Archive.EntryFilter)null, new ArchiveEntryFilter()))); + } + } + + private List getClassPathArchives(String path) throws Exception { + String root = PropertiesLauncher.this.cleanupPath(PropertiesLauncher.this.handleUrl(path)); + List lib = new ArrayList(); + File file = new File(root); + if (!"/".equals(root)) { + if (!this.isAbsolutePath(root)) { + file = new File(PropertiesLauncher.this.home, root); + } + + if (file.isDirectory()) { + PropertiesLauncher.this.debug("Adding classpath entries from " + file); + Archive archive = new ExplodedArchive(file, false); + lib.add(archive); + } + } + + Archive archive = this.getArchive(file); + if (archive != null) { + PropertiesLauncher.this.debug("Adding classpath entries from archive " + archive.getUrl() + root); + lib.add(archive); + } + + List nestedArchives = this.getNestedArchives(root); + if (nestedArchives != null) { + PropertiesLauncher.this.debug("Adding classpath entries from nested " + root); + lib.addAll(nestedArchives); + } + + return lib; + } + + private boolean isAbsolutePath(String root) { + return root.contains(":") || root.startsWith("/"); + } + + private Archive getArchive(File file) throws IOException { + if (this.isNestedArchivePath(file)) { + return null; + } else { + String name = file.getName().toLowerCase(Locale.ENGLISH); + return !name.endsWith(".jar") && !name.endsWith(".zip") ? null : this.getJarFileArchive(file); + } + } + + private boolean isNestedArchivePath(File file) { + return file.getPath().contains(PropertiesLauncher.NESTED_ARCHIVE_SEPARATOR); + } + + private List getNestedArchives(String path) throws Exception { + Archive parent = PropertiesLauncher.this.parent; + String root = path; + if ((path.equals("/") || !path.startsWith("/")) && !parent.getUrl().toURI().equals(PropertiesLauncher.this.home.toURI())) { + int index = path.indexOf(33); + if (index != -1) { + File file = new File(PropertiesLauncher.this.home, path.substring(0, index)); + if (path.startsWith("jar:file:")) { + file = new File(path.substring("jar:file:".length(), index)); + } + + parent = this.getJarFileArchive(file); + + for(root = path.substring(index + 1); root.startsWith("/"); root = root.substring(1)) { + } + } + + if (root.endsWith(".jar")) { + File file = new File(PropertiesLauncher.this.home, root); + if (file.exists()) { + parent = this.getJarFileArchive(file); + root = ""; + } + } + + if (root.equals("/") || root.equals("./") || root.equals(".")) { + root = ""; + } + + Archive.EntryFilter filter = new PrefixMatchingArchiveFilter(root); + List archives = this.asList(parent.getNestedArchives((Archive.EntryFilter)null, filter)); + if ((root == null || root.isEmpty() || ".".equals(root)) && !path.endsWith(".jar") && parent != PropertiesLauncher.this.parent) { + archives.add(parent); + } + + return archives; + } else { + return null; + } + } + + private void addNestedEntries() { + try { + Iterator archives = PropertiesLauncher.this.parent.getNestedArchives((Archive.EntryFilter)null, JarLauncher.NESTED_ARCHIVE_ENTRY_FILTER); + + while(archives.hasNext()) { + this.classPathArchives.add(archives.next()); + } + } catch (IOException var2) { + } + + } + + private List asList(Iterator iterator) { + List list = new ArrayList(); + + while(iterator.hasNext()) { + list.add(iterator.next()); + } + + return list; + } + + private JarFileArchive getJarFileArchive(File file) throws IOException { + JarFileArchive archive = new JarFileArchive(file); + this.jarFileArchives.add(archive); + return archive; + } + + public Iterator iterator() { + return this.classPathArchives.iterator(); + } + + void close() throws IOException { + for(JarFileArchive archive : this.jarFileArchives) { + archive.close(); + } + + } + } + + private static final class PrefixMatchingArchiveFilter implements Archive.EntryFilter { + private final String prefix; + private final ArchiveEntryFilter filter; + + private PrefixMatchingArchiveFilter(String prefix) { + this.filter = new ArchiveEntryFilter(); + this.prefix = prefix; + } + + public boolean matches(Archive.Entry entry) { + if (entry.isDirectory()) { + return entry.getName().equals(this.prefix); + } else { + return entry.getName().startsWith(this.prefix) && this.filter.matches(entry); + } + } + } + + private static final class ArchiveEntryFilter implements Archive.EntryFilter { + private static final String DOT_JAR = ".jar"; + private static final String DOT_ZIP = ".zip"; + + private ArchiveEntryFilter() { + } + + public boolean matches(Archive.Entry entry) { + return entry.getName().endsWith(".jar") || entry.getName().endsWith(".zip"); + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/WarLauncher.java b/src/main/java/org/springframework/boot/loader/WarLauncher.java new file mode 100644 index 0000000..76b8f51 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/WarLauncher.java @@ -0,0 +1,32 @@ +package org.springframework.boot.loader; + +import org.springframework.boot.loader.archive.Archive; + +public class WarLauncher extends ExecutableArchiveLauncher { + public WarLauncher() { + } + + protected WarLauncher(Archive archive) { + super(archive); + } + + protected boolean isPostProcessingClassPathArchives() { + return false; + } + + public boolean isNestedArchive(Archive.Entry entry) { + if (entry.isDirectory()) { + return entry.getName().equals("WEB-INF/classes/"); + } else { + return entry.getName().startsWith("WEB-INF/lib/") || entry.getName().startsWith("WEB-INF/lib-provided/"); + } + } + + protected String getArchiveEntryPathPrefix() { + return "WEB-INF/"; + } + + public static void main(String[] args) throws Exception { + (new WarLauncher()).launch(args); + } +} diff --git a/src/main/java/org/springframework/boot/loader/archive/Archive.java b/src/main/java/org/springframework/boot/loader/archive/Archive.java new file mode 100644 index 0000000..014d102 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/archive/Archive.java @@ -0,0 +1,69 @@ +package org.springframework.boot.loader.archive; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; +import java.util.jar.Manifest; + +public interface Archive extends Iterable, AutoCloseable { + URL getUrl() throws MalformedURLException; + + Manifest getManifest() throws IOException; + + default Iterator getNestedArchives(EntryFilter searchFilter, EntryFilter includeFilter) throws IOException { + EntryFilter combinedFilter = (entry) -> (searchFilter == null || searchFilter.matches(entry)) && (includeFilter == null || includeFilter.matches(entry)); + List nestedArchives = this.getNestedArchives(combinedFilter); + return nestedArchives.iterator(); + } + + /** @deprecated */ + @Deprecated + default List getNestedArchives(EntryFilter filter) throws IOException { + throw new IllegalStateException("Unexpected call to getNestedArchives(filter)"); + } + + /** @deprecated */ + @Deprecated + Iterator iterator(); + + /** @deprecated */ + @Deprecated + default void forEach(Consumer action) { + Objects.requireNonNull(action); + + for(Entry entry : this) { + action.accept(entry); + } + + } + + /** @deprecated */ + @Deprecated + default Spliterator spliterator() { + return Spliterators.spliteratorUnknownSize(this.iterator(), 0); + } + + default boolean isExploded() { + return false; + } + + default void close() throws Exception { + } + + public interface Entry { + boolean isDirectory(); + + String getName(); + } + + @FunctionalInterface + public interface EntryFilter { + boolean matches(Entry entry); + } +} diff --git a/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java b/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java new file mode 100644 index 0000000..e771b42 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java @@ -0,0 +1,276 @@ +package org.springframework.boot.loader.archive; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Deque; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.jar.Manifest; + +public class ExplodedArchive implements Archive { + private static final Set SKIPPED_NAMES = new HashSet(Arrays.asList(".", "..")); + private final File root; + private final boolean recursive; + private File manifestFile; + private Manifest manifest; + + public ExplodedArchive(File root) { + this(root, true); + } + + public ExplodedArchive(File root, boolean recursive) { + if (root.exists() && root.isDirectory()) { + this.root = root; + this.recursive = recursive; + this.manifestFile = this.getManifestFile(root); + } else { + throw new IllegalArgumentException("Invalid source directory " + root); + } + } + + private File getManifestFile(File root) { + File metaInf = new File(root, "META-INF"); + return new File(metaInf, "MANIFEST.MF"); + } + + public URL getUrl() throws MalformedURLException { + return this.root.toURI().toURL(); + } + + public Manifest getManifest() throws IOException { + if (this.manifest == null && this.manifestFile.exists()) { + FileInputStream inputStream = new FileInputStream(this.manifestFile); + Throwable var2 = null; + + try { + this.manifest = new Manifest(inputStream); + } catch (Throwable var11) { + var2 = var11; + throw var11; + } finally { + if (inputStream != null) { + if (var2 != null) { + try { + inputStream.close(); + } catch (Throwable var10) { + var2.addSuppressed(var10); + } + } else { + inputStream.close(); + } + } + + } + } + + return this.manifest; + } + + public Iterator getNestedArchives(Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) throws IOException { + return new ArchiveIterator(this.root, this.recursive, searchFilter, includeFilter); + } + + /** @deprecated */ + @Deprecated + public Iterator iterator() { + return new EntryIterator(this.root, this.recursive, (Archive.EntryFilter)null, (Archive.EntryFilter)null); + } + + protected Archive getNestedArchive(Archive.Entry entry) throws IOException { + File file = ((FileEntry)entry).getFile(); + return (Archive)(file.isDirectory() ? new ExplodedArchive(file) : new SimpleJarFileArchive((FileEntry)entry)); + } + + public boolean isExploded() { + return true; + } + + public String toString() { + try { + return this.getUrl().toString(); + } catch (Exception var2) { + return "exploded archive"; + } + } + + private abstract static class AbstractIterator implements Iterator { + private static final Comparator entryComparator = Comparator.comparing(File::getAbsolutePath); + private final File root; + private final boolean recursive; + private final Archive.EntryFilter searchFilter; + private final Archive.EntryFilter includeFilter; + private final Deque stack = new LinkedList(); + private FileEntry current; + private String rootUrl; + + AbstractIterator(File root, boolean recursive, Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) { + this.root = root; + this.rootUrl = this.root.toURI().getPath(); + this.recursive = recursive; + this.searchFilter = searchFilter; + this.includeFilter = includeFilter; + this.stack.add(this.listFiles(root)); + this.current = this.poll(); + } + + public boolean hasNext() { + return this.current != null; + } + + public Object next() { + FileEntry entry = this.current; + if (entry == null) { + throw new NoSuchElementException(); + } else { + this.current = this.poll(); + return this.adapt(entry); + } + } + + private FileEntry poll() { + while(!this.stack.isEmpty()) { + if (!((Iterator)this.stack.peek()).hasNext()) { + this.stack.poll(); + } else { + File file = (File)((Iterator)this.stack.peek()).next(); + if (!ExplodedArchive.SKIPPED_NAMES.contains(file.getName())) { + FileEntry entry = this.getFileEntry(file); + if (this.isListable(entry)) { + this.stack.addFirst(this.listFiles(file)); + } + + if (this.includeFilter == null || this.includeFilter.matches(entry)) { + return entry; + } + } + } + } + + return null; + } + + private FileEntry getFileEntry(File file) { + URI uri = file.toURI(); + String name = uri.getPath().substring(this.rootUrl.length()); + + try { + return new FileEntry(name, file, uri.toURL()); + } catch (MalformedURLException ex) { + throw new IllegalStateException(ex); + } + } + + private boolean isListable(FileEntry entry) { + return entry.isDirectory() && (this.recursive || entry.getFile().getParentFile().equals(this.root)) && (this.searchFilter == null || this.searchFilter.matches(entry)) && (this.includeFilter == null || !this.includeFilter.matches(entry)); + } + + private Iterator listFiles(File file) { + File[] files = file.listFiles(); + if (files == null) { + return Collections.emptyIterator(); + } else { + Arrays.sort(files, entryComparator); + return Arrays.asList(files).iterator(); + } + } + + public void remove() { + throw new UnsupportedOperationException("remove"); + } + + protected abstract Object adapt(FileEntry entry); + } + + private static class EntryIterator extends AbstractIterator { + EntryIterator(File root, boolean recursive, Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) { + super(root, recursive, searchFilter, includeFilter); + } + + protected Archive.Entry adapt(FileEntry entry) { + return entry; + } + } + + private static class ArchiveIterator extends AbstractIterator { + ArchiveIterator(File root, boolean recursive, Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) { + super(root, recursive, searchFilter, includeFilter); + } + + protected Archive adapt(FileEntry entry) { + File file = entry.getFile(); + return (Archive)(file.isDirectory() ? new ExplodedArchive(file) : new SimpleJarFileArchive(entry)); + } + } + + private static class FileEntry implements Archive.Entry { + private final String name; + private final File file; + private final URL url; + + FileEntry(String name, File file, URL url) { + this.name = name; + this.file = file; + this.url = url; + } + + File getFile() { + return this.file; + } + + public boolean isDirectory() { + return this.file.isDirectory(); + } + + public String getName() { + return this.name; + } + + URL getUrl() { + return this.url; + } + } + + private static class SimpleJarFileArchive implements Archive { + private final URL url; + + SimpleJarFileArchive(FileEntry file) { + this.url = file.getUrl(); + } + + public URL getUrl() throws MalformedURLException { + return this.url; + } + + public Manifest getManifest() throws IOException { + return null; + } + + public Iterator getNestedArchives(Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) throws IOException { + return Collections.emptyIterator(); + } + + /** @deprecated */ + @Deprecated + public Iterator iterator() { + return Collections.emptyIterator(); + } + + public String toString() { + try { + return this.getUrl().toString(); + } catch (Exception var2) { + return "jar archive"; + } + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java b/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java new file mode 100644 index 0000000..b21cbac --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java @@ -0,0 +1,290 @@ +package org.springframework.boot.loader.archive; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.UUID; +import java.util.jar.JarEntry; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import org.springframework.boot.loader.jar.JarFile; + +public class JarFileArchive implements Archive { + private static final String UNPACK_MARKER = "UNPACK:"; + private static final int BUFFER_SIZE = 32768; + private static final FileAttribute[] NO_FILE_ATTRIBUTES = new FileAttribute[0]; + private static final EnumSet DIRECTORY_PERMISSIONS; + private static final EnumSet FILE_PERMISSIONS; + private final JarFile jarFile; + private URL url; + private Path tempUnpackDirectory; + + public JarFileArchive(File file) throws IOException { + this(file, file.toURI().toURL()); + } + + public JarFileArchive(File file, URL url) throws IOException { + this(new JarFile(file)); + this.url = url; + } + + public JarFileArchive(JarFile jarFile) { + this.jarFile = jarFile; + } + + public URL getUrl() throws MalformedURLException { + return this.url != null ? this.url : this.jarFile.getUrl(); + } + + public Manifest getManifest() throws IOException { + return this.jarFile.getManifest(); + } + + public Iterator getNestedArchives(Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) throws IOException { + return new NestedArchiveIterator(this.jarFile.iterator(), searchFilter, includeFilter); + } + + /** @deprecated */ + @Deprecated + public Iterator iterator() { + return new EntryIterator(this.jarFile.iterator(), (Archive.EntryFilter)null, (Archive.EntryFilter)null); + } + + public void close() throws IOException { + this.jarFile.close(); + } + + protected Archive getNestedArchive(Archive.Entry entry) throws IOException { + JarEntry jarEntry = ((JarFileEntry)entry).getJarEntry(); + if (jarEntry.getComment().startsWith("UNPACK:")) { + return this.getUnpackedNestedArchive(jarEntry); + } else { + try { + JarFile jarFile = this.jarFile.getNestedJarFile((ZipEntry)jarEntry); + return new JarFileArchive(jarFile); + } catch (Exception ex) { + throw new IllegalStateException("Failed to get nested archive for entry " + entry.getName(), ex); + } + } + } + + private Archive getUnpackedNestedArchive(JarEntry jarEntry) throws IOException { + String name = jarEntry.getName(); + if (name.lastIndexOf(47) != -1) { + name = name.substring(name.lastIndexOf(47) + 1); + } + + Path path = this.getTempUnpackDirectory().resolve(name); + if (!Files.exists(path, new LinkOption[0]) || Files.size(path) != jarEntry.getSize()) { + this.unpack(jarEntry, path); + } + + return new JarFileArchive(path.toFile(), path.toUri().toURL()); + } + + private Path getTempUnpackDirectory() { + if (this.tempUnpackDirectory == null) { + Path tempDirectory = Paths.get(System.getProperty("java.io.tmpdir")); + this.tempUnpackDirectory = this.createUnpackDirectory(tempDirectory); + } + + return this.tempUnpackDirectory; + } + + private Path createUnpackDirectory(Path parent) { + int attempts = 0; + + while(attempts++ < 1000) { + String fileName = Paths.get(this.jarFile.getName()).getFileName().toString(); + Path unpackDirectory = parent.resolve(fileName + "-spring-boot-libs-" + UUID.randomUUID()); + + try { + this.createDirectory(unpackDirectory); + return unpackDirectory; + } catch (IOException var6) { + } + } + + throw new IllegalStateException("Failed to create unpack directory in directory '" + parent + "'"); + } + + private void unpack(JarEntry entry, Path path) throws IOException { + this.createFile(path); + path.toFile().deleteOnExit(); + InputStream inputStream = this.jarFile.getInputStream((ZipEntry)entry); + Throwable var4 = null; + + try { + OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); + Throwable var6 = null; + + try { + byte[] buffer = new byte['耀']; + + int bytesRead; + while((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + + outputStream.flush(); + } catch (Throwable var30) { + var6 = var30; + throw var30; + } finally { + if (outputStream != null) { + if (var6 != null) { + try { + outputStream.close(); + } catch (Throwable var29) { + var6.addSuppressed(var29); + } + } else { + outputStream.close(); + } + } + + } + } catch (Throwable var32) { + var4 = var32; + throw var32; + } finally { + if (inputStream != null) { + if (var4 != null) { + try { + inputStream.close(); + } catch (Throwable var28) { + var4.addSuppressed(var28); + } + } else { + inputStream.close(); + } + } + + } + + } + + private void createDirectory(Path path) throws IOException { + Files.createDirectory(path, this.getFileAttributes(path.getFileSystem(), DIRECTORY_PERMISSIONS)); + } + + private void createFile(Path path) throws IOException { + Files.createFile(path, this.getFileAttributes(path.getFileSystem(), FILE_PERMISSIONS)); + } + + private FileAttribute[] getFileAttributes(FileSystem fileSystem, EnumSet ownerReadWrite) { + return !fileSystem.supportedFileAttributeViews().contains("posix") ? NO_FILE_ATTRIBUTES : new FileAttribute[]{PosixFilePermissions.asFileAttribute(ownerReadWrite)}; + } + + public String toString() { + try { + return this.getUrl().toString(); + } catch (Exception var2) { + return "jar archive"; + } + } + + static { + DIRECTORY_PERMISSIONS = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE); + FILE_PERMISSIONS = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE); + } + + private abstract static class AbstractIterator implements Iterator { + private final Iterator iterator; + private final Archive.EntryFilter searchFilter; + private final Archive.EntryFilter includeFilter; + private Archive.Entry current; + + AbstractIterator(Iterator iterator, Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) { + this.iterator = iterator; + this.searchFilter = searchFilter; + this.includeFilter = includeFilter; + this.current = this.poll(); + } + + public boolean hasNext() { + return this.current != null; + } + + public Object next() { + T result = (T)this.adapt(this.current); + this.current = this.poll(); + return result; + } + + private Archive.Entry poll() { + while(true) { + if (this.iterator.hasNext()) { + JarFileEntry candidate = new JarFileEntry((JarEntry)this.iterator.next()); + if (this.searchFilter != null && !this.searchFilter.matches(candidate) || this.includeFilter != null && !this.includeFilter.matches(candidate)) { + continue; + } + + return candidate; + } + + return null; + } + } + + protected abstract Object adapt(Archive.Entry entry); + } + + private static class EntryIterator extends AbstractIterator { + EntryIterator(Iterator iterator, Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) { + super(iterator, searchFilter, includeFilter); + } + + protected Archive.Entry adapt(Archive.Entry entry) { + return entry; + } + } + + private class NestedArchiveIterator extends AbstractIterator { + NestedArchiveIterator(Iterator iterator, Archive.EntryFilter searchFilter, Archive.EntryFilter includeFilter) { + super(iterator, searchFilter, includeFilter); + } + + protected Archive adapt(Archive.Entry entry) { + try { + return JarFileArchive.this.getNestedArchive(entry); + } catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + } + + private static class JarFileEntry implements Archive.Entry { + private final JarEntry jarEntry; + + JarFileEntry(JarEntry jarEntry) { + this.jarEntry = jarEntry; + } + + JarEntry getJarEntry() { + return this.jarEntry; + } + + public boolean isDirectory() { + return this.jarEntry.isDirectory(); + } + + public String getName() { + return this.jarEntry.getName(); + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/data/RandomAccessData.java b/src/main/java/org/springframework/boot/loader/data/RandomAccessData.java new file mode 100644 index 0000000..25d98dd --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/data/RandomAccessData.java @@ -0,0 +1,16 @@ +package org.springframework.boot.loader.data; + +import java.io.IOException; +import java.io.InputStream; + +public interface RandomAccessData { + InputStream getInputStream() throws IOException; + + RandomAccessData getSubsection(long offset, long length); + + byte[] read() throws IOException; + + byte[] read(long offset, long length) throws IOException; + + long getSize(); +} diff --git a/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java b/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java new file mode 100644 index 0000000..d3eef95 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/data/RandomAccessDataFile.java @@ -0,0 +1,181 @@ +package org.springframework.boot.loader.data; + +import java.io.EOFException; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; + +public class RandomAccessDataFile implements RandomAccessData { + private final FileAccess fileAccess; + private final long offset; + private final long length; + + public RandomAccessDataFile(File file) { + if (file == null) { + throw new IllegalArgumentException("File must not be null"); + } else { + this.fileAccess = new FileAccess(file); + this.offset = 0L; + this.length = file.length(); + } + } + + private RandomAccessDataFile(FileAccess fileAccess, long offset, long length) { + this.fileAccess = fileAccess; + this.offset = offset; + this.length = length; + } + + public File getFile() { + return this.fileAccess.file; + } + + public InputStream getInputStream() throws IOException { + return new DataInputStream(); + } + + public RandomAccessData getSubsection(long offset, long length) { + if (offset >= 0L && length >= 0L && offset + length <= this.length) { + return new RandomAccessDataFile(this.fileAccess, this.offset + offset, length); + } else { + throw new IndexOutOfBoundsException(); + } + } + + public byte[] read() throws IOException { + return this.read(0L, this.length); + } + + public byte[] read(long offset, long length) throws IOException { + if (offset > this.length) { + throw new IndexOutOfBoundsException(); + } else if (offset + length > this.length) { + throw new EOFException(); + } else { + byte[] bytes = new byte[(int)length]; + this.read(bytes, offset, 0, bytes.length); + return bytes; + } + } + + private int readByte(long position) throws IOException { + return position >= this.length ? -1 : this.fileAccess.readByte(this.offset + position); + } + + private int read(byte[] bytes, long position, int offset, int length) throws IOException { + return position > this.length ? -1 : this.fileAccess.read(bytes, this.offset + position, offset, length); + } + + public long getSize() { + return this.length; + } + + public void close() throws IOException { + this.fileAccess.close(); + } + + private class DataInputStream extends InputStream { + private int position; + + private DataInputStream() { + } + + public int read() throws IOException { + int read = RandomAccessDataFile.this.readByte((long)this.position); + if (read > -1) { + this.moveOn(1); + } + + return read; + } + + public int read(byte[] b) throws IOException { + return this.read(b, 0, b != null ? b.length : 0); + } + + public int read(byte[] b, int off, int len) throws IOException { + if (b == null) { + throw new NullPointerException("Bytes must not be null"); + } else { + return this.doRead(b, off, len); + } + } + + int doRead(byte[] b, int off, int len) throws IOException { + if (len == 0) { + return 0; + } else { + int cappedLen = this.cap((long)len); + return cappedLen <= 0 ? -1 : (int)this.moveOn(RandomAccessDataFile.this.read(b, (long)this.position, off, cappedLen)); + } + } + + public long skip(long n) throws IOException { + return n <= 0L ? 0L : this.moveOn(this.cap(n)); + } + + public int available() throws IOException { + return (int)RandomAccessDataFile.this.length - this.position; + } + + private int cap(long n) { + return (int)Math.min(RandomAccessDataFile.this.length - (long)this.position, n); + } + + private long moveOn(int amount) { + this.position += amount; + return (long)amount; + } + } + + private static final class FileAccess { + private final Object monitor; + private final File file; + private RandomAccessFile randomAccessFile; + + private FileAccess(File file) { + this.monitor = new Object(); + this.file = file; + this.openIfNecessary(); + } + + private int read(byte[] bytes, long position, int offset, int length) throws IOException { + synchronized(this.monitor) { + this.openIfNecessary(); + this.randomAccessFile.seek(position); + return this.randomAccessFile.read(bytes, offset, length); + } + } + + private void openIfNecessary() { + if (this.randomAccessFile == null) { + try { + this.randomAccessFile = new RandomAccessFile(this.file, "r"); + } catch (FileNotFoundException var2) { + throw new IllegalArgumentException(String.format("File %s must exist", this.file.getAbsolutePath())); + } + } + + } + + private void close() throws IOException { + synchronized(this.monitor) { + if (this.randomAccessFile != null) { + this.randomAccessFile.close(); + this.randomAccessFile = null; + } + + } + } + + private int readByte(long position) throws IOException { + synchronized(this.monitor) { + this.openIfNecessary(); + this.randomAccessFile.seek(position); + return this.randomAccessFile.read(); + } + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/AbstractJarFile.java b/src/main/java/org/springframework/boot/loader/jar/AbstractJarFile.java new file mode 100644 index 0000000..232d312 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/AbstractJarFile.java @@ -0,0 +1,28 @@ +package org.springframework.boot.loader.jar; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.Permission; + +abstract class AbstractJarFile extends java.util.jar.JarFile { + AbstractJarFile(File file) throws IOException { + super(file); + } + + abstract URL getUrl() throws MalformedURLException; + + abstract JarFileType getType(); + + abstract Permission getPermission(); + + abstract InputStream getInputStream() throws IOException; + + static enum JarFileType { + DIRECT, + NESTED_DIRECTORY, + NESTED_JAR; + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java b/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java new file mode 100644 index 0000000..6db893f --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/AsciiBytes.java @@ -0,0 +1,214 @@ +package org.springframework.boot.loader.jar; + +import java.nio.charset.StandardCharsets; + +final class AsciiBytes { + private static final String EMPTY_STRING = ""; + private static final int[] INITIAL_BYTE_BITMASK = new int[]{127, 31, 15, 7}; + private static final int SUBSEQUENT_BYTE_BITMASK = 63; + private final byte[] bytes; + private final int offset; + private final int length; + private String string; + private int hash; + + AsciiBytes(String string) { + this(string.getBytes(StandardCharsets.UTF_8)); + this.string = string; + } + + AsciiBytes(byte[] bytes) { + this(bytes, 0, bytes.length); + } + + AsciiBytes(byte[] bytes, int offset, int length) { + if (offset >= 0 && length >= 0 && offset + length <= bytes.length) { + this.bytes = bytes; + this.offset = offset; + this.length = length; + } else { + throw new IndexOutOfBoundsException(); + } + } + + int length() { + return this.length; + } + + boolean startsWith(AsciiBytes prefix) { + if (this == prefix) { + return true; + } else if (prefix.length > this.length) { + return false; + } else { + for(int i = 0; i < prefix.length; ++i) { + if (this.bytes[i + this.offset] != prefix.bytes[i + prefix.offset]) { + return false; + } + } + + return true; + } + } + + boolean endsWith(AsciiBytes postfix) { + if (this == postfix) { + return true; + } else if (postfix.length > this.length) { + return false; + } else { + for(int i = 0; i < postfix.length; ++i) { + if (this.bytes[this.offset + (this.length - 1) - i] != postfix.bytes[postfix.offset + (postfix.length - 1) - i]) { + return false; + } + } + + return true; + } + } + + AsciiBytes substring(int beginIndex) { + return this.substring(beginIndex, this.length); + } + + AsciiBytes substring(int beginIndex, int endIndex) { + int length = endIndex - beginIndex; + if (this.offset + length > this.bytes.length) { + throw new IndexOutOfBoundsException(); + } else { + return new AsciiBytes(this.bytes, this.offset + beginIndex, length); + } + } + + boolean matches(CharSequence name, char suffix) { + int charIndex = 0; + int nameLen = name.length(); + int totalLen = nameLen + (suffix != 0 ? 1 : 0); + + for(int i = this.offset; i < this.offset + this.length; ++i) { + int b = this.bytes[i]; + int remainingUtfBytes = this.getNumberOfUtfBytes(b) - 1; + b &= INITIAL_BYTE_BITMASK[remainingUtfBytes]; + + for(int j = 0; j < remainingUtfBytes; ++j) { + int var10000 = b << 6; + ++i; + b = var10000 + (this.bytes[i] & 63); + } + + char c = this.getChar(name, suffix, charIndex++); + if (b <= 65535) { + if (c != b) { + return false; + } + } else { + if (c != (b >> 10) + 'ퟀ') { + return false; + } + + c = this.getChar(name, suffix, charIndex++); + if (c != (b & 1023) + '\udc00') { + return false; + } + } + } + + return charIndex == totalLen; + } + + private char getChar(CharSequence name, char suffix, int index) { + if (index < name.length()) { + return name.charAt(index); + } else { + return index == name.length() ? suffix : '\u0000'; + } + } + + private int getNumberOfUtfBytes(int b) { + if ((b & 128) == 0) { + return 1; + } else { + int numberOfUtfBytes; + for(numberOfUtfBytes = 0; (b & 128) != 0; ++numberOfUtfBytes) { + b <<= 1; + } + + return numberOfUtfBytes; + } + } + + public boolean equals(Object obj) { + if (obj == null) { + return false; + } else if (this == obj) { + return true; + } else { + if (obj.getClass() == AsciiBytes.class) { + AsciiBytes other = (AsciiBytes)obj; + if (this.length == other.length) { + for(int i = 0; i < this.length; ++i) { + if (this.bytes[this.offset + i] != other.bytes[other.offset + i]) { + return false; + } + } + + return true; + } + } + + return false; + } + } + + public int hashCode() { + int hash = this.hash; + if (hash == 0 && this.bytes.length > 0) { + for(int i = this.offset; i < this.offset + this.length; ++i) { + int b = this.bytes[i]; + int remainingUtfBytes = this.getNumberOfUtfBytes(b) - 1; + b &= INITIAL_BYTE_BITMASK[remainingUtfBytes]; + + for(int j = 0; j < remainingUtfBytes; ++j) { + int var10000 = b << 6; + ++i; + b = var10000 + (this.bytes[i] & 63); + } + + if (b <= 65535) { + hash = 31 * hash + b; + } else { + hash = 31 * hash + (b >> 10) + 'ퟀ'; + hash = 31 * hash + (b & 1023) + '\udc00'; + } + } + + this.hash = hash; + } + + return hash; + } + + public String toString() { + if (this.string == null) { + if (this.length == 0) { + this.string = ""; + } else { + this.string = new String(this.bytes, this.offset, this.length, StandardCharsets.UTF_8); + } + } + + return this.string; + } + + static String toString(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + static int hashCode(CharSequence charSequence) { + return charSequence instanceof StringSequence ? charSequence.hashCode() : charSequence.toString().hashCode(); + } + + static int hashCode(int hash, char suffix) { + return suffix != 0 ? 31 * hash + suffix : hash; + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/Bytes.java b/src/main/java/org/springframework/boot/loader/jar/Bytes.java new file mode 100644 index 0000000..ae9982e --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/Bytes.java @@ -0,0 +1,16 @@ +package org.springframework.boot.loader.jar; + +final class Bytes { + private Bytes() { + } + + static long littleEndianValue(byte[] bytes, int offset, int length) { + long value = 0L; + + for(int i = length - 1; i >= 0; --i) { + value = value << 8 | (long)(bytes[offset + i] & 255); + } + + return value; + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java new file mode 100644 index 0000000..e58b18c --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryEndRecord.java @@ -0,0 +1,152 @@ +package org.springframework.boot.loader.jar; + +import java.io.IOException; +import org.springframework.boot.loader.data.RandomAccessData; + +class CentralDirectoryEndRecord { + private static final int MINIMUM_SIZE = 22; + private static final int MAXIMUM_COMMENT_LENGTH = 65535; + private static final int MAXIMUM_SIZE = 65557; + private static final int SIGNATURE = 101010256; + private static final int COMMENT_LENGTH_OFFSET = 20; + private static final int READ_BLOCK_SIZE = 256; + private final Zip64End zip64End; + private byte[] block; + private int offset; + private int size; + + CentralDirectoryEndRecord(RandomAccessData data) throws IOException { + this.block = this.createBlockFromEndOfData(data, 256); + this.size = 22; + + for(this.offset = this.block.length - this.size; !this.isValid(); this.offset = this.block.length - this.size) { + ++this.size; + if (this.size > this.block.length) { + if (this.size >= 65557 || (long)this.size > data.getSize()) { + throw new IOException("Unable to find ZIP central directory records after reading " + this.size + " bytes"); + } + + this.block = this.createBlockFromEndOfData(data, this.size + 256); + } + } + + long startOfCentralDirectoryEndRecord = data.getSize() - (long)this.size; + Zip64Locator zip64Locator = CentralDirectoryEndRecord.Zip64Locator.find(data, startOfCentralDirectoryEndRecord); + this.zip64End = zip64Locator != null ? new Zip64End(data, zip64Locator) : null; + } + + private byte[] createBlockFromEndOfData(RandomAccessData data, int size) throws IOException { + int length = (int)Math.min(data.getSize(), (long)size); + return data.read(data.getSize() - (long)length, (long)length); + } + + private boolean isValid() { + if (this.block.length >= 22 && Bytes.littleEndianValue(this.block, this.offset + 0, 4) == 101010256L) { + long commentLength = Bytes.littleEndianValue(this.block, this.offset + 20, 2); + return (long)this.size == 22L + commentLength; + } else { + return false; + } + } + + long getStartOfArchive(RandomAccessData data) { + long length = Bytes.littleEndianValue(this.block, this.offset + 12, 4); + long specifiedOffset = this.zip64End != null ? this.zip64End.centralDirectoryOffset : Bytes.littleEndianValue(this.block, this.offset + 16, 4); + long zip64EndSize = this.zip64End != null ? this.zip64End.getSize() : 0L; + int zip64LocSize = this.zip64End != null ? 20 : 0; + long actualOffset = data.getSize() - (long)this.size - length - zip64EndSize - (long)zip64LocSize; + return actualOffset - specifiedOffset; + } + + RandomAccessData getCentralDirectory(RandomAccessData data) { + if (this.zip64End != null) { + return this.zip64End.getCentralDirectory(data); + } else { + long offset = Bytes.littleEndianValue(this.block, this.offset + 16, 4); + long length = Bytes.littleEndianValue(this.block, this.offset + 12, 4); + return data.getSubsection(offset, length); + } + } + + int getNumberOfRecords() { + if (this.zip64End != null) { + return this.zip64End.getNumberOfRecords(); + } else { + long numberOfRecords = Bytes.littleEndianValue(this.block, this.offset + 10, 2); + return (int)numberOfRecords; + } + } + + String getComment() { + int commentLength = (int)Bytes.littleEndianValue(this.block, this.offset + 20, 2); + AsciiBytes comment = new AsciiBytes(this.block, this.offset + 20 + 2, commentLength); + return comment.toString(); + } + + boolean isZip64() { + return this.zip64End != null; + } + + private static final class Zip64End { + private static final int ZIP64_ENDTOT = 32; + private static final int ZIP64_ENDSIZ = 40; + private static final int ZIP64_ENDOFF = 48; + private final Zip64Locator locator; + private final long centralDirectoryOffset; + private final long centralDirectoryLength; + private final int numberOfRecords; + + private Zip64End(RandomAccessData data, Zip64Locator locator) throws IOException { + this.locator = locator; + byte[] block = data.read(locator.getZip64EndOffset(), 56L); + this.centralDirectoryOffset = Bytes.littleEndianValue(block, 48, 8); + this.centralDirectoryLength = Bytes.littleEndianValue(block, 40, 8); + this.numberOfRecords = (int)Bytes.littleEndianValue(block, 32, 8); + } + + private long getSize() { + return this.locator.getZip64EndSize(); + } + + private RandomAccessData getCentralDirectory(RandomAccessData data) { + return data.getSubsection(this.centralDirectoryOffset, this.centralDirectoryLength); + } + + private int getNumberOfRecords() { + return this.numberOfRecords; + } + } + + private static final class Zip64Locator { + static final int SIGNATURE = 117853008; + static final int ZIP64_LOCSIZE = 20; + static final int ZIP64_LOCOFF = 8; + private final long zip64EndOffset; + private final long offset; + + private Zip64Locator(long offset, byte[] block) { + this.offset = offset; + this.zip64EndOffset = Bytes.littleEndianValue(block, 8, 8); + } + + private long getZip64EndSize() { + return this.offset - this.zip64EndOffset; + } + + private long getZip64EndOffset() { + return this.zip64EndOffset; + } + + private static Zip64Locator find(RandomAccessData data, long centralDirectoryEndOffset) throws IOException { + long offset = centralDirectoryEndOffset - 20L; + if (offset >= 0L) { + byte[] block = data.read(offset, 20L); + if (Bytes.littleEndianValue(block, 0, 4) == 117853008L) { + return new Zip64Locator(offset, block); + } + } + + return null; + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java new file mode 100644 index 0000000..e452340 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java @@ -0,0 +1,172 @@ +package org.springframework.boot.loader.jar; + +import java.io.IOException; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoField; +import java.time.temporal.ChronoUnit; +import java.time.temporal.ValueRange; +import org.springframework.boot.loader.data.RandomAccessData; + +final class CentralDirectoryFileHeader implements FileHeader { + private static final AsciiBytes SLASH = new AsciiBytes("/"); + private static final byte[] NO_EXTRA = new byte[0]; + private static final AsciiBytes NO_COMMENT = new AsciiBytes(""); + private byte[] header; + private int headerOffset; + private AsciiBytes name; + private byte[] extra; + private AsciiBytes comment; + private long localHeaderOffset; + + CentralDirectoryFileHeader() { + } + + CentralDirectoryFileHeader(byte[] header, int headerOffset, AsciiBytes name, byte[] extra, AsciiBytes comment, long localHeaderOffset) { + this.header = header; + this.headerOffset = headerOffset; + this.name = name; + this.extra = extra; + this.comment = comment; + this.localHeaderOffset = localHeaderOffset; + } + + void load(byte[] data, int dataOffset, RandomAccessData variableData, long variableOffset, JarEntryFilter filter) throws IOException { + this.header = data; + this.headerOffset = dataOffset; + long compressedSize = Bytes.littleEndianValue(data, dataOffset + 20, 4); + long uncompressedSize = Bytes.littleEndianValue(data, dataOffset + 24, 4); + long nameLength = Bytes.littleEndianValue(data, dataOffset + 28, 2); + long extraLength = Bytes.littleEndianValue(data, dataOffset + 30, 2); + long commentLength = Bytes.littleEndianValue(data, dataOffset + 32, 2); + long localHeaderOffset = Bytes.littleEndianValue(data, dataOffset + 42, 4); + dataOffset += 46; + if (variableData != null) { + data = variableData.read(variableOffset + 46L, nameLength + extraLength + commentLength); + dataOffset = 0; + } + + this.name = new AsciiBytes(data, dataOffset, (int)nameLength); + if (filter != null) { + this.name = filter.apply(this.name); + } + + this.extra = NO_EXTRA; + this.comment = NO_COMMENT; + if (extraLength > 0L) { + this.extra = new byte[(int)extraLength]; + System.arraycopy(data, (int)((long)dataOffset + nameLength), this.extra, 0, this.extra.length); + } + + this.localHeaderOffset = this.getLocalHeaderOffset(compressedSize, uncompressedSize, localHeaderOffset, this.extra); + if (commentLength > 0L) { + this.comment = new AsciiBytes(data, (int)((long)dataOffset + nameLength + extraLength), (int)commentLength); + } + + } + + private long getLocalHeaderOffset(long compressedSize, long uncompressedSize, long localHeaderOffset, byte[] extra) throws IOException { + if (localHeaderOffset != 4294967295L) { + return localHeaderOffset; + } else { + int length; + int extraOffset; + for(extraOffset = 0; extraOffset < extra.length - 2; extraOffset += length) { + int id = (int)Bytes.littleEndianValue(extra, extraOffset, 2); + length = (int)Bytes.littleEndianValue(extra, extraOffset, 2); + extraOffset += 4; + if (id == 1) { + int localHeaderExtraOffset = 0; + if (compressedSize == 4294967295L) { + localHeaderExtraOffset += 4; + } + + if (uncompressedSize == 4294967295L) { + localHeaderExtraOffset += 4; + } + + return Bytes.littleEndianValue(extra, extraOffset + localHeaderExtraOffset, 8); + } + } + + throw new IOException("Zip64 Extended Information Extra Field not found"); + } + } + + AsciiBytes getName() { + return this.name; + } + + public boolean hasName(CharSequence name, char suffix) { + return this.name.matches(name, suffix); + } + + boolean isDirectory() { + return this.name.endsWith(SLASH); + } + + public int getMethod() { + return (int)Bytes.littleEndianValue(this.header, this.headerOffset + 10, 2); + } + + long getTime() { + long datetime = Bytes.littleEndianValue(this.header, this.headerOffset + 12, 4); + return this.decodeMsDosFormatDateTime(datetime); + } + + private long decodeMsDosFormatDateTime(long datetime) { + int year = getChronoValue((datetime >> 25 & 127L) + 1980L, ChronoField.YEAR); + int month = getChronoValue(datetime >> 21 & 15L, ChronoField.MONTH_OF_YEAR); + int day = getChronoValue(datetime >> 16 & 31L, ChronoField.DAY_OF_MONTH); + int hour = getChronoValue(datetime >> 11 & 31L, ChronoField.HOUR_OF_DAY); + int minute = getChronoValue(datetime >> 5 & 63L, ChronoField.MINUTE_OF_HOUR); + int second = getChronoValue(datetime << 1 & 62L, ChronoField.SECOND_OF_MINUTE); + return ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.SECONDS).toEpochMilli(); + } + + long getCrc() { + return Bytes.littleEndianValue(this.header, this.headerOffset + 16, 4); + } + + public long getCompressedSize() { + return Bytes.littleEndianValue(this.header, this.headerOffset + 20, 4); + } + + public long getSize() { + return Bytes.littleEndianValue(this.header, this.headerOffset + 24, 4); + } + + byte[] getExtra() { + return this.extra; + } + + boolean hasExtra() { + return this.extra.length > 0; + } + + AsciiBytes getComment() { + return this.comment; + } + + public long getLocalHeaderOffset() { + return this.localHeaderOffset; + } + + public CentralDirectoryFileHeader clone() { + byte[] header = new byte[46]; + System.arraycopy(this.header, this.headerOffset, header, 0, header.length); + return new CentralDirectoryFileHeader(header, 0, this.name, header, this.comment, this.localHeaderOffset); + } + + static CentralDirectoryFileHeader fromRandomAccessData(RandomAccessData data, long offset, JarEntryFilter filter) throws IOException { + CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); + byte[] bytes = data.read(offset, 46L); + fileHeader.load(bytes, 0, data, offset, filter); + return fileHeader; + } + + private static int getChronoValue(long value, ChronoField field) { + ValueRange range = field.range(); + return Math.toIntExact(Math.min(Math.max(value, range.getMinimum()), range.getMaximum())); + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java new file mode 100644 index 0000000..5c42c52 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryParser.java @@ -0,0 +1,68 @@ +package org.springframework.boot.loader.jar; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.springframework.boot.loader.data.RandomAccessData; + +class CentralDirectoryParser { + private static final int CENTRAL_DIRECTORY_HEADER_BASE_SIZE = 46; + private final List visitors = new ArrayList(); + + CentralDirectoryVisitor addVisitor(CentralDirectoryVisitor visitor) { + this.visitors.add(visitor); + return visitor; + } + + RandomAccessData parse(RandomAccessData data, boolean skipPrefixBytes) throws IOException { + CentralDirectoryEndRecord endRecord = new CentralDirectoryEndRecord(data); + if (skipPrefixBytes) { + data = this.getArchiveData(endRecord, data); + } + + RandomAccessData centralDirectoryData = endRecord.getCentralDirectory(data); + this.visitStart(endRecord, centralDirectoryData); + this.parseEntries(endRecord, centralDirectoryData); + this.visitEnd(); + return data; + } + + private void parseEntries(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) throws IOException { + byte[] bytes = centralDirectoryData.read(0L, centralDirectoryData.getSize()); + CentralDirectoryFileHeader fileHeader = new CentralDirectoryFileHeader(); + int dataOffset = 0; + + for(int i = 0; i < endRecord.getNumberOfRecords(); ++i) { + fileHeader.load(bytes, dataOffset, (RandomAccessData)null, 0L, (JarEntryFilter)null); + this.visitFileHeader((long)dataOffset, fileHeader); + dataOffset += 46 + fileHeader.getName().length() + fileHeader.getComment().length() + fileHeader.getExtra().length; + } + + } + + private RandomAccessData getArchiveData(CentralDirectoryEndRecord endRecord, RandomAccessData data) { + long offset = endRecord.getStartOfArchive(data); + return offset == 0L ? data : data.getSubsection(offset, data.getSize() - offset); + } + + private void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { + for(CentralDirectoryVisitor visitor : this.visitors) { + visitor.visitStart(endRecord, centralDirectoryData); + } + + } + + private void visitFileHeader(long dataOffset, CentralDirectoryFileHeader fileHeader) { + for(CentralDirectoryVisitor visitor : this.visitors) { + visitor.visitFileHeader(fileHeader, dataOffset); + } + + } + + private void visitEnd() { + for(CentralDirectoryVisitor visitor : this.visitors) { + visitor.visitEnd(); + } + + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java new file mode 100644 index 0000000..d8884a0 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryVisitor.java @@ -0,0 +1,11 @@ +package org.springframework.boot.loader.jar; + +import org.springframework.boot.loader.data.RandomAccessData; + +interface CentralDirectoryVisitor { + void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData); + + void visitFileHeader(CentralDirectoryFileHeader fileHeader, long dataOffset); + + void visitEnd(); +} diff --git a/src/main/java/org/springframework/boot/loader/jar/FileHeader.java b/src/main/java/org/springframework/boot/loader/jar/FileHeader.java new file mode 100644 index 0000000..2f05459 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/FileHeader.java @@ -0,0 +1,13 @@ +package org.springframework.boot.loader.jar; + +interface FileHeader { + boolean hasName(CharSequence name, char suffix); + + long getLocalHeaderOffset(); + + long getCompressedSize(); + + long getSize(); + + int getMethod(); +} diff --git a/src/main/java/org/springframework/boot/loader/jar/Handler.java b/src/main/java/org/springframework/boot/loader/jar/Handler.java new file mode 100644 index 0000000..17f2fbf --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/Handler.java @@ -0,0 +1,390 @@ +package org.springframework.boot.loader.jar; + +import java.io.File; +import java.io.IOException; +import java.lang.ref.SoftReference; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +public class Handler extends URLStreamHandler { + private static final String JAR_PROTOCOL = "jar:"; + private static final String FILE_PROTOCOL = "file:"; + private static final String TOMCAT_WARFILE_PROTOCOL = "war:file:"; + private static final String SEPARATOR = "!/"; + private static final Pattern SEPARATOR_PATTERN = Pattern.compile("!/", 16); + private static final String CURRENT_DIR = "/./"; + private static final Pattern CURRENT_DIR_PATTERN = Pattern.compile("/./", 16); + private static final String PARENT_DIR = "/../"; + private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; + private static final String[] FALLBACK_HANDLERS = new String[]{"sun.net.www.protocol.jar.Handler"}; + private static URL jarContextUrl; + private static SoftReference rootFileCache = new SoftReference((Object)null); + private final JarFile jarFile; + private URLStreamHandler fallbackHandler; + + public Handler() { + this((JarFile)null); + } + + public Handler(JarFile jarFile) { + this.jarFile = jarFile; + } + + protected URLConnection openConnection(URL url) throws IOException { + if (this.jarFile != null && this.isUrlInJarFile(url, this.jarFile)) { + return JarURLConnection.get(url, this.jarFile); + } else { + try { + return JarURLConnection.get(url, this.getRootJarFileFromUrl(url)); + } catch (Exception ex) { + return this.openFallbackConnection(url, ex); + } + } + } + + private boolean isUrlInJarFile(URL url, JarFile jarFile) throws MalformedURLException { + return url.getPath().startsWith(jarFile.getUrl().getPath()) && url.toString().startsWith(jarFile.getUrlString()); + } + + private URLConnection openFallbackConnection(URL url, Exception reason) throws IOException { + try { + URLConnection connection = this.openFallbackTomcatConnection(url); + connection = connection != null ? connection : this.openFallbackContextConnection(url); + return connection != null ? connection : this.openFallbackHandlerConnection(url); + } catch (Exception ex) { + if (reason instanceof IOException) { + this.log(false, "Unable to open fallback handler", ex); + throw (IOException)reason; + } else { + this.log(true, "Unable to open fallback handler", ex); + if (reason instanceof RuntimeException) { + throw (RuntimeException)reason; + } else { + throw new IllegalStateException(reason); + } + } + } + } + + private URLConnection openFallbackTomcatConnection(URL url) { + String file = url.getFile(); + if (this.isTomcatWarUrl(file)) { + file = file.substring("war:file:".length()); + file = file.replaceFirst("\\*/", "!/"); + + try { + URLConnection connection = this.openConnection(new URL("jar:file:" + file)); + connection.getInputStream().close(); + return connection; + } catch (IOException var4) { + } + } + + return null; + } + + private boolean isTomcatWarUrl(String file) { + if (file.startsWith("war:file:") || !file.contains("*/")) { + try { + URLConnection connection = (new URL(file)).openConnection(); + if (connection.getClass().getName().startsWith("org.apache.catalina")) { + return true; + } + } catch (Exception var3) { + } + } + + return false; + } + + private URLConnection openFallbackContextConnection(URL url) { + try { + if (jarContextUrl != null) { + return (new URL(jarContextUrl, url.toExternalForm())).openConnection(); + } + } catch (Exception var3) { + } + + return null; + } + + private URLConnection openFallbackHandlerConnection(URL url) throws Exception { + URLStreamHandler fallbackHandler = this.getFallbackHandler(); + return (new URL((URL)null, url.toExternalForm(), fallbackHandler)).openConnection(); + } + + private URLStreamHandler getFallbackHandler() { + if (this.fallbackHandler != null) { + return this.fallbackHandler; + } else { + for(String handlerClassName : FALLBACK_HANDLERS) { + try { + Class handlerClass = Class.forName(handlerClassName); + this.fallbackHandler = (URLStreamHandler)handlerClass.getDeclaredConstructor().newInstance(); + return this.fallbackHandler; + } catch (Exception var6) { + } + } + + throw new IllegalStateException("Unable to find fallback handler"); + } + } + + private void log(boolean warning, String message, Exception cause) { + try { + Level level = warning ? Level.WARNING : Level.FINEST; + Logger.getLogger(this.getClass().getName()).log(level, message, cause); + } catch (Exception var5) { + if (warning) { + System.err.println("WARNING: " + message); + } + } + + } + + protected void parseURL(URL context, String spec, int start, int limit) { + if (spec.regionMatches(true, 0, "jar:", 0, "jar:".length())) { + this.setFile(context, this.getFileFromSpec(spec.substring(start, limit))); + } else { + this.setFile(context, this.getFileFromContext(context, spec.substring(start, limit))); + } + + } + + private String getFileFromSpec(String spec) { + int separatorIndex = spec.lastIndexOf("!/"); + if (separatorIndex == -1) { + throw new IllegalArgumentException("No !/ in spec '" + spec + "'"); + } else { + try { + new URL(spec.substring(0, separatorIndex)); + return spec; + } catch (MalformedURLException ex) { + throw new IllegalArgumentException("Invalid spec URL '" + spec + "'", ex); + } + } + } + + private String getFileFromContext(URL context, String spec) { + String file = context.getFile(); + if (spec.startsWith("/")) { + return this.trimToJarRoot(file) + "!/" + spec.substring(1); + } else if (file.endsWith("/")) { + return file + spec; + } else { + int lastSlashIndex = file.lastIndexOf(47); + if (lastSlashIndex == -1) { + throw new IllegalArgumentException("No / found in context URL's file '" + file + "'"); + } else { + return file.substring(0, lastSlashIndex + 1) + spec; + } + } + } + + private String trimToJarRoot(String file) { + int lastSeparatorIndex = file.lastIndexOf("!/"); + if (lastSeparatorIndex == -1) { + throw new IllegalArgumentException("No !/ found in context URL's file '" + file + "'"); + } else { + return file.substring(0, lastSeparatorIndex); + } + } + + private void setFile(URL context, String file) { + String path = this.normalize(file); + String query = null; + int queryIndex = path.lastIndexOf(63); + if (queryIndex != -1) { + query = path.substring(queryIndex + 1); + path = path.substring(0, queryIndex); + } + + this.setURL(context, "jar:", (String)null, -1, (String)null, (String)null, path, query, context.getRef()); + } + + private String normalize(String file) { + if (!file.contains("/./") && !file.contains("/../")) { + return file; + } else { + int afterLastSeparatorIndex = file.lastIndexOf("!/") + "!/".length(); + String afterSeparator = file.substring(afterLastSeparatorIndex); + afterSeparator = this.replaceParentDir(afterSeparator); + afterSeparator = this.replaceCurrentDir(afterSeparator); + return file.substring(0, afterLastSeparatorIndex) + afterSeparator; + } + } + + private String replaceParentDir(String file) { + int parentDirIndex; + while((parentDirIndex = file.indexOf("/../")) >= 0) { + int precedingSlashIndex = file.lastIndexOf(47, parentDirIndex - 1); + if (precedingSlashIndex >= 0) { + file = file.substring(0, precedingSlashIndex) + file.substring(parentDirIndex + 3); + } else { + file = file.substring(parentDirIndex + 4); + } + } + + return file; + } + + private String replaceCurrentDir(String file) { + return CURRENT_DIR_PATTERN.matcher(file).replaceAll("/"); + } + + protected int hashCode(URL u) { + return this.hashCode(u.getProtocol(), u.getFile()); + } + + private int hashCode(String protocol, String file) { + int result = protocol != null ? protocol.hashCode() : 0; + int separatorIndex = file.indexOf("!/"); + if (separatorIndex == -1) { + return result + file.hashCode(); + } else { + String source = file.substring(0, separatorIndex); + String entry = this.canonicalize(file.substring(separatorIndex + 2)); + + try { + result += (new URL(source)).hashCode(); + } catch (MalformedURLException var8) { + result += source.hashCode(); + } + + result += entry.hashCode(); + return result; + } + } + + protected boolean sameFile(URL u1, URL u2) { + if (u1.getProtocol().equals("jar") && u2.getProtocol().equals("jar")) { + int separator1 = u1.getFile().indexOf("!/"); + int separator2 = u2.getFile().indexOf("!/"); + if (separator1 != -1 && separator2 != -1) { + String nested1 = u1.getFile().substring(separator1 + "!/".length()); + String nested2 = u2.getFile().substring(separator2 + "!/".length()); + if (!nested1.equals(nested2)) { + String canonical1 = this.canonicalize(nested1); + String canonical2 = this.canonicalize(nested2); + if (!canonical1.equals(canonical2)) { + return false; + } + } + + String root1 = u1.getFile().substring(0, separator1); + String root2 = u2.getFile().substring(0, separator2); + + try { + return super.sameFile(new URL(root1), new URL(root2)); + } catch (MalformedURLException var10) { + return super.sameFile(u1, u2); + } + } else { + return super.sameFile(u1, u2); + } + } else { + return false; + } + } + + private String canonicalize(String path) { + return SEPARATOR_PATTERN.matcher(path).replaceAll("/"); + } + + public JarFile getRootJarFileFromUrl(URL url) throws IOException { + String spec = url.getFile(); + int separatorIndex = spec.indexOf("!/"); + if (separatorIndex == -1) { + throw new MalformedURLException("Jar URL does not contain !/ separator"); + } else { + String name = spec.substring(0, separatorIndex); + return this.getRootJarFile(name); + } + } + + private JarFile getRootJarFile(String name) throws IOException { + try { + if (!name.startsWith("file:")) { + throw new IllegalStateException("Not a file URL"); + } else { + File file = new File(URI.create(name)); + Map cache = (Map)rootFileCache.get(); + JarFile result = cache != null ? (JarFile)cache.get(file) : null; + if (result == null) { + result = new JarFile(file); + addToRootFileCache(file, result); + } + + return result; + } + } catch (Exception ex) { + throw new IOException("Unable to open root Jar file '" + name + "'", ex); + } + } + + static void addToRootFileCache(File sourceFile, JarFile jarFile) { + Map cache = (Map)rootFileCache.get(); + if (cache == null) { + cache = new ConcurrentHashMap(); + rootFileCache = new SoftReference(cache); + } + + cache.put(sourceFile, jarFile); + } + + static void captureJarContextUrl() { + if (canResetCachedUrlHandlers()) { + String handlers = System.getProperty("java.protocol.handler.pkgs"); + + try { + System.clearProperty("java.protocol.handler.pkgs"); + + try { + resetCachedUrlHandlers(); + jarContextUrl = new URL("jar:file:context.jar!/"); + URLConnection connection = jarContextUrl.openConnection(); + if (connection instanceof JarURLConnection) { + jarContextUrl = null; + } + } catch (Exception var5) { + } + } finally { + if (handlers == null) { + System.clearProperty("java.protocol.handler.pkgs"); + } else { + System.setProperty("java.protocol.handler.pkgs", handlers); + } + + } + + resetCachedUrlHandlers(); + } + + } + + private static boolean canResetCachedUrlHandlers() { + try { + resetCachedUrlHandlers(); + return true; + } catch (Error var1) { + return false; + } + } + + private static void resetCachedUrlHandlers() { + URL.setURLStreamHandlerFactory((URLStreamHandlerFactory)null); + } + + public static void setUseFastConnectionExceptions(boolean useFastConnectionExceptions) { + JarURLConnection.setUseFastExceptions(useFastConnectionExceptions); + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/JarEntry.java b/src/main/java/org/springframework/boot/loader/jar/JarEntry.java new file mode 100644 index 0000000..79aabf9 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/JarEntry.java @@ -0,0 +1,84 @@ +package org.springframework.boot.loader.jar; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.CodeSigner; +import java.security.cert.Certificate; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +class JarEntry extends java.util.jar.JarEntry implements FileHeader { + private final int index; + private final AsciiBytes name; + private final AsciiBytes headerName; + private final JarFile jarFile; + private long localHeaderOffset; + private volatile JarEntryCertification certification; + + JarEntry(JarFile jarFile, int index, CentralDirectoryFileHeader header, AsciiBytes nameAlias) { + super(nameAlias != null ? nameAlias.toString() : header.getName().toString()); + this.index = index; + this.name = nameAlias != null ? nameAlias : header.getName(); + this.headerName = header.getName(); + this.jarFile = jarFile; + this.localHeaderOffset = header.getLocalHeaderOffset(); + this.setCompressedSize(header.getCompressedSize()); + this.setMethod(header.getMethod()); + this.setCrc(header.getCrc()); + this.setComment(header.getComment().toString()); + this.setSize(header.getSize()); + this.setTime(header.getTime()); + if (header.hasExtra()) { + this.setExtra(header.getExtra()); + } + + } + + int getIndex() { + return this.index; + } + + AsciiBytes getAsciiBytesName() { + return this.name; + } + + public boolean hasName(CharSequence name, char suffix) { + return this.headerName.matches(name, suffix); + } + + URL getUrl() throws MalformedURLException { + return new URL(this.jarFile.getUrl(), this.getName()); + } + + public Attributes getAttributes() throws IOException { + Manifest manifest = this.jarFile.getManifest(); + return manifest != null ? manifest.getAttributes(this.getName()) : null; + } + + public Certificate[] getCertificates() { + return this.getCertification().getCertificates(); + } + + public CodeSigner[] getCodeSigners() { + return this.getCertification().getCodeSigners(); + } + + private JarEntryCertification getCertification() { + if (!this.jarFile.isSigned()) { + return JarEntryCertification.NONE; + } else { + JarEntryCertification certification = this.certification; + if (certification == null) { + certification = this.jarFile.getCertification(this); + this.certification = certification; + } + + return certification; + } + } + + public long getLocalHeaderOffset() { + return this.localHeaderOffset; + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/JarEntryCertification.java b/src/main/java/org/springframework/boot/loader/jar/JarEntryCertification.java new file mode 100644 index 0000000..7240403 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/JarEntryCertification.java @@ -0,0 +1,29 @@ +package org.springframework.boot.loader.jar; + +import java.security.CodeSigner; +import java.security.cert.Certificate; + +class JarEntryCertification { + static final JarEntryCertification NONE = new JarEntryCertification((Certificate[])null, (CodeSigner[])null); + private final Certificate[] certificates; + private final CodeSigner[] codeSigners; + + JarEntryCertification(Certificate[] certificates, CodeSigner[] codeSigners) { + this.certificates = certificates; + this.codeSigners = codeSigners; + } + + Certificate[] getCertificates() { + return this.certificates != null ? (Certificate[])this.certificates.clone() : null; + } + + CodeSigner[] getCodeSigners() { + return this.codeSigners != null ? (CodeSigner[])this.codeSigners.clone() : null; + } + + static JarEntryCertification from(java.util.jar.JarEntry certifiedEntry) { + Certificate[] certificates = certifiedEntry != null ? certifiedEntry.getCertificates() : null; + CodeSigner[] codeSigners = certifiedEntry != null ? certifiedEntry.getCodeSigners() : null; + return certificates == null && codeSigners == null ? NONE : new JarEntryCertification(certificates, codeSigners); + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/JarEntryFilter.java b/src/main/java/org/springframework/boot/loader/jar/JarEntryFilter.java new file mode 100644 index 0000000..1935613 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/JarEntryFilter.java @@ -0,0 +1,5 @@ +package org.springframework.boot.loader.jar; + +interface JarEntryFilter { + AsciiBytes apply(AsciiBytes name); +} diff --git a/src/main/java/org/springframework/boot/loader/jar/JarFile.java b/src/main/java/org/springframework/boot/loader/jar/JarFile.java new file mode 100644 index 0000000..4846664 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/JarFile.java @@ -0,0 +1,361 @@ +package org.springframework.boot.loader.jar; + +import java.io.File; +import java.io.FilePermission; +import java.io.IOException; +import java.io.InputStream; +import java.lang.ref.SoftReference; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLStreamHandlerFactory; +import java.security.Permission; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Supplier; +import java.util.jar.Manifest; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import java.util.zip.ZipEntry; +import org.springframework.boot.loader.data.RandomAccessData; +import org.springframework.boot.loader.data.RandomAccessDataFile; + +public class JarFile extends AbstractJarFile implements Iterable { + private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; + private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; + private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader"; + private static final AsciiBytes META_INF = new AsciiBytes("META-INF/"); + private static final AsciiBytes SIGNATURE_FILE_EXTENSION = new AsciiBytes(".SF"); + private static final String READ_ACTION = "read"; + private final RandomAccessDataFile rootFile; + private final String pathFromRoot; + private final RandomAccessData data; + private final AbstractJarFile.JarFileType type; + private URL url; + private String urlString; + private JarFileEntries entries; + private Supplier manifestSupplier; + private SoftReference manifest; + private boolean signed; + private String comment; + private volatile boolean closed; + private volatile JarFileWrapper wrapper; + + public JarFile(File file) throws IOException { + this(new RandomAccessDataFile(file)); + } + + JarFile(RandomAccessDataFile file) throws IOException { + this(file, "", file, AbstractJarFile.JarFileType.DIRECT); + } + + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, AbstractJarFile.JarFileType type) throws IOException { + this(rootFile, pathFromRoot, data, (JarEntryFilter)null, type, (Supplier)null); + } + + private JarFile(RandomAccessDataFile rootFile, String pathFromRoot, RandomAccessData data, JarEntryFilter filter, AbstractJarFile.JarFileType type, Supplier manifestSupplier) throws IOException { + super(rootFile.getFile()); + if (System.getSecurityManager() == null) { + super.close(); + } + + this.rootFile = rootFile; + this.pathFromRoot = pathFromRoot; + CentralDirectoryParser parser = new CentralDirectoryParser(); + this.entries = (JarFileEntries)parser.addVisitor(new JarFileEntries(this, filter)); + this.type = type; + parser.addVisitor(this.centralDirectoryVisitor()); + + try { + this.data = parser.parse(data, filter == null); + } catch (RuntimeException ex) { + try { + this.rootFile.close(); + super.close(); + } catch (IOException var10) { + } + + throw ex; + } + + this.manifestSupplier = manifestSupplier != null ? manifestSupplier : () -> { + try { + InputStream inputStream = this.getInputStream("META-INF/MANIFEST.MF"); + Throwable var2 = null; + + Manifest var3; + try { + if (inputStream != null) { + var3 = new Manifest(inputStream); + return var3; + } + + var3 = null; + } catch (Throwable var14) { + var2 = var14; + throw var14; + } finally { + if (inputStream != null) { + if (var2 != null) { + try { + inputStream.close(); + } catch (Throwable var13) { + var2.addSuppressed(var13); + } + } else { + inputStream.close(); + } + } + + } + + return var3; + } catch (IOException ex) { + throw new RuntimeException(ex); + } + }; + } + + private CentralDirectoryVisitor centralDirectoryVisitor() { + return new CentralDirectoryVisitor() { + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { + JarFile.this.comment = endRecord.getComment(); + } + + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, long dataOffset) { + AsciiBytes name = fileHeader.getName(); + if (name.startsWith(JarFile.META_INF) && name.endsWith(JarFile.SIGNATURE_FILE_EXTENSION)) { + JarFile.this.signed = true; + } + + } + + public void visitEnd() { + } + }; + } + + JarFileWrapper getWrapper() throws IOException { + JarFileWrapper wrapper = this.wrapper; + if (wrapper == null) { + wrapper = new JarFileWrapper(this); + this.wrapper = wrapper; + } + + return wrapper; + } + + Permission getPermission() { + return new FilePermission(this.rootFile.getFile().getPath(), "read"); + } + + protected final RandomAccessDataFile getRootJarFile() { + return this.rootFile; + } + + RandomAccessData getData() { + return this.data; + } + + public Manifest getManifest() throws IOException { + Manifest manifest = this.manifest != null ? (Manifest)this.manifest.get() : null; + if (manifest == null) { + try { + manifest = (Manifest)this.manifestSupplier.get(); + } catch (RuntimeException ex) { + throw new IOException(ex); + } + + this.manifest = new SoftReference(manifest); + } + + return manifest; + } + + public Enumeration entries() { + return new JarEntryEnumeration(this.entries.iterator()); + } + + public Stream stream() { + Spliterator spliterator = Spliterators.spliterator(this.iterator(), (long)this.size(), 1297); + return StreamSupport.stream(spliterator, false); + } + + public Iterator iterator() { + return this.entries.iterator(this::ensureOpen); + } + + public JarEntry getJarEntry(CharSequence name) { + return this.entries.getEntry(name); + } + + public JarEntry getJarEntry(String name) { + return (JarEntry)this.getEntry(name); + } + + public boolean containsEntry(String name) { + return this.entries.containsEntry(name); + } + + public ZipEntry getEntry(String name) { + this.ensureOpen(); + return this.entries.getEntry(name); + } + + InputStream getInputStream() throws IOException { + return this.data.getInputStream(); + } + + public synchronized InputStream getInputStream(ZipEntry entry) throws IOException { + this.ensureOpen(); + return entry instanceof JarEntry ? this.entries.getInputStream((FileHeader)((JarEntry)entry)) : this.getInputStream(entry != null ? entry.getName() : null); + } + + InputStream getInputStream(String name) throws IOException { + return this.entries.getInputStream(name); + } + + public synchronized JarFile getNestedJarFile(ZipEntry entry) throws IOException { + return this.getNestedJarFile((JarEntry)entry); + } + + public synchronized JarFile getNestedJarFile(JarEntry entry) throws IOException { + try { + return this.createJarFileFromEntry(entry); + } catch (Exception ex) { + throw new IOException("Unable to open nested jar file '" + entry.getName() + "'", ex); + } + } + + private JarFile createJarFileFromEntry(JarEntry entry) throws IOException { + return entry.isDirectory() ? this.createJarFileFromDirectoryEntry(entry) : this.createJarFileFromFileEntry(entry); + } + + private JarFile createJarFileFromDirectoryEntry(JarEntry entry) throws IOException { + AsciiBytes name = entry.getAsciiBytesName(); + JarEntryFilter filter = (candidate) -> candidate.startsWith(name) && !candidate.equals(name) ? candidate.substring(name.length()) : null; + return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName().substring(0, name.length() - 1), this.data, filter, AbstractJarFile.JarFileType.NESTED_DIRECTORY, this.manifestSupplier); + } + + private JarFile createJarFileFromFileEntry(JarEntry entry) throws IOException { + if (entry.getMethod() != 0) { + throw new IllegalStateException("Unable to open nested entry '" + entry.getName() + "'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file"); + } else { + RandomAccessData entryData = this.entries.getEntryData(entry.getName()); + return new JarFile(this.rootFile, this.pathFromRoot + "!/" + entry.getName(), entryData, AbstractJarFile.JarFileType.NESTED_JAR); + } + } + + public String getComment() { + this.ensureOpen(); + return this.comment; + } + + public int size() { + this.ensureOpen(); + return this.entries.getSize(); + } + + public void close() throws IOException { + if (!this.closed) { + super.close(); + if (this.type == AbstractJarFile.JarFileType.DIRECT) { + this.rootFile.close(); + } + + this.closed = true; + } + } + + private void ensureOpen() { + if (this.closed) { + throw new IllegalStateException("zip file closed"); + } + } + + boolean isClosed() { + return this.closed; + } + + String getUrlString() throws MalformedURLException { + if (this.urlString == null) { + this.urlString = this.getUrl().toString(); + } + + return this.urlString; + } + + public URL getUrl() throws MalformedURLException { + if (this.url == null) { + String file = this.rootFile.getFile().toURI() + this.pathFromRoot + "!/"; + file = file.replace("file:////", "file://"); + this.url = new URL("jar", "", -1, file, new Handler(this)); + } + + return this.url; + } + + public String toString() { + return this.getName(); + } + + public String getName() { + return this.rootFile.getFile() + this.pathFromRoot; + } + + boolean isSigned() { + return this.signed; + } + + JarEntryCertification getCertification(JarEntry entry) { + try { + return this.entries.getCertification(entry); + } catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + public void clearCache() { + this.entries.clearCache(); + } + + protected String getPathFromRoot() { + return this.pathFromRoot; + } + + AbstractJarFile.JarFileType getType() { + return this.type; + } + + public static void registerUrlProtocolHandler() { + Handler.captureJarContextUrl(); + String handlers = System.getProperty("java.protocol.handler.pkgs", ""); + System.setProperty("java.protocol.handler.pkgs", handlers != null && !handlers.isEmpty() ? handlers + "|" + "org.springframework.boot.loader" : "org.springframework.boot.loader"); + resetCachedUrlHandlers(); + } + + private static void resetCachedUrlHandlers() { + try { + URL.setURLStreamHandlerFactory((URLStreamHandlerFactory)null); + } catch (Error var1) { + } + + } + + private static class JarEntryEnumeration implements Enumeration { + private final Iterator iterator; + + JarEntryEnumeration(Iterator iterator) { + this.iterator = iterator; + } + + public boolean hasMoreElements() { + return this.iterator.hasNext(); + } + + public java.util.jar.JarEntry nextElement() { + return (java.util.jar.JarEntry)this.iterator.next(); + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java b/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java new file mode 100644 index 0000000..9aa77f9 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java @@ -0,0 +1,435 @@ +package org.springframework.boot.loader.jar; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.jar.Attributes; +import java.util.jar.JarInputStream; +import java.util.jar.Manifest; +import org.springframework.boot.loader.data.RandomAccessData; + +class JarFileEntries implements CentralDirectoryVisitor, Iterable { + private static final Runnable NO_VALIDATION = () -> { + }; + private static final String META_INF_PREFIX = "META-INF/"; + private static final Attributes.Name MULTI_RELEASE = new Attributes.Name("Multi-Release"); + private static final int BASE_VERSION = 8; + private static final int RUNTIME_VERSION; + private static final long LOCAL_FILE_HEADER_SIZE = 30L; + private static final char SLASH = '/'; + private static final char NO_SUFFIX = '\u0000'; + protected static final int ENTRY_CACHE_SIZE = 25; + private final JarFile jarFile; + private final JarEntryFilter filter; + private RandomAccessData centralDirectoryData; + private int size; + private int[] hashCodes; + private Offsets centralDirectoryOffsets; + private int[] positions; + private Boolean multiReleaseJar; + private JarEntryCertification[] certifications; + private final Map entriesCache = Collections.synchronizedMap(new LinkedHashMap(16, 0.75F, true) { + protected boolean removeEldestEntry(Map.Entry eldest) { + return this.size() >= 25; + } + }); + + JarFileEntries(JarFile jarFile, JarEntryFilter filter) { + this.jarFile = jarFile; + this.filter = filter; + if (RUNTIME_VERSION == 8) { + this.multiReleaseJar = false; + } + + } + + public void visitStart(CentralDirectoryEndRecord endRecord, RandomAccessData centralDirectoryData) { + int maxSize = endRecord.getNumberOfRecords(); + this.centralDirectoryData = centralDirectoryData; + this.hashCodes = new int[maxSize]; + this.centralDirectoryOffsets = JarFileEntries.Offsets.from(endRecord); + this.positions = new int[maxSize]; + } + + public void visitFileHeader(CentralDirectoryFileHeader fileHeader, long dataOffset) { + AsciiBytes name = this.applyFilter(fileHeader.getName()); + if (name != null) { + this.add(name, dataOffset); + } + + } + + private void add(AsciiBytes name, long dataOffset) { + this.hashCodes[this.size] = name.hashCode(); + this.centralDirectoryOffsets.set(this.size, dataOffset); + this.positions[this.size] = this.size++; + } + + public void visitEnd() { + this.sort(0, this.size - 1); + int[] positions = this.positions; + this.positions = new int[positions.length]; + + for(int i = 0; i < this.size; this.positions[positions[i]] = i++) { + } + + } + + int getSize() { + return this.size; + } + + private void sort(int left, int right) { + if (left < right) { + int pivot = this.hashCodes[left + (right - left) / 2]; + int i = left; + int j = right; + + while(i <= j) { + while(this.hashCodes[i] < pivot) { + ++i; + } + + while(this.hashCodes[j] > pivot) { + --j; + } + + if (i <= j) { + this.swap(i, j); + ++i; + --j; + } + } + + if (left < j) { + this.sort(left, j); + } + + if (right > i) { + this.sort(i, right); + } + } + + } + + private void swap(int i, int j) { + swap(this.hashCodes, i, j); + this.centralDirectoryOffsets.swap(i, j); + swap(this.positions, i, j); + } + + public Iterator iterator() { + return new EntryIterator(NO_VALIDATION); + } + + Iterator iterator(Runnable validator) { + return new EntryIterator(validator); + } + + boolean containsEntry(CharSequence name) { + return this.getEntry(name, FileHeader.class, true) != null; + } + + JarEntry getEntry(CharSequence name) { + return (JarEntry)this.getEntry(name, JarEntry.class, true); + } + + InputStream getInputStream(String name) throws IOException { + FileHeader entry = this.getEntry(name, FileHeader.class, false); + return this.getInputStream(entry); + } + + InputStream getInputStream(FileHeader entry) throws IOException { + if (entry == null) { + return null; + } else { + InputStream inputStream = this.getEntryData(entry).getInputStream(); + if (entry.getMethod() == 8) { + inputStream = new ZipInflaterInputStream(inputStream, (int)entry.getSize()); + } + + return inputStream; + } + } + + RandomAccessData getEntryData(String name) throws IOException { + FileHeader entry = this.getEntry(name, FileHeader.class, false); + return entry == null ? null : this.getEntryData(entry); + } + + private RandomAccessData getEntryData(FileHeader entry) throws IOException { + RandomAccessData data = this.jarFile.getData(); + byte[] localHeader = data.read(entry.getLocalHeaderOffset(), 30L); + long nameLength = Bytes.littleEndianValue(localHeader, 26, 2); + long extraLength = Bytes.littleEndianValue(localHeader, 28, 2); + return data.getSubsection(entry.getLocalHeaderOffset() + 30L + nameLength + extraLength, entry.getCompressedSize()); + } + + private FileHeader getEntry(CharSequence name, Class type, boolean cacheEntry) { + T entry = (T)this.doGetEntry(name, type, cacheEntry, (AsciiBytes)null); + if (!this.isMetaInfEntry(name) && this.isMultiReleaseJar()) { + int version = RUNTIME_VERSION; + + for(AsciiBytes nameAlias = entry instanceof JarEntry ? ((JarEntry)entry).getAsciiBytesName() : new AsciiBytes(name.toString()); version > 8; --version) { + T versionedEntry = (T)this.doGetEntry("META-INF/versions/" + version + "/" + name, type, cacheEntry, nameAlias); + if (versionedEntry != null) { + return versionedEntry; + } + } + } + + return entry; + } + + private boolean isMetaInfEntry(CharSequence name) { + return name.toString().startsWith("META-INF/"); + } + + private boolean isMultiReleaseJar() { + Boolean multiRelease = this.multiReleaseJar; + if (multiRelease != null) { + return multiRelease; + } else { + try { + Manifest manifest = this.jarFile.getManifest(); + if (manifest == null) { + multiRelease = false; + } else { + Attributes attributes = manifest.getMainAttributes(); + multiRelease = attributes.containsKey(MULTI_RELEASE); + } + } catch (IOException var4) { + multiRelease = false; + } + + this.multiReleaseJar = multiRelease; + return multiRelease; + } + } + + private FileHeader doGetEntry(CharSequence name, Class type, boolean cacheEntry, AsciiBytes nameAlias) { + int hashCode = AsciiBytes.hashCode(name); + T entry = (T)this.getEntry(hashCode, name, '\u0000', type, cacheEntry, nameAlias); + if (entry == null) { + hashCode = AsciiBytes.hashCode(hashCode, '/'); + entry = (T)this.getEntry(hashCode, name, '/', type, cacheEntry, nameAlias); + } + + return entry; + } + + private FileHeader getEntry(int hashCode, CharSequence name, char suffix, Class type, boolean cacheEntry, AsciiBytes nameAlias) { + for(int index = this.getFirstIndex(hashCode); index >= 0 && index < this.size && this.hashCodes[index] == hashCode; ++index) { + T entry = (T)this.getEntry(index, type, cacheEntry, nameAlias); + if (entry.hasName(name, suffix)) { + return entry; + } + } + + return null; + } + + private FileHeader getEntry(int index, Class type, boolean cacheEntry, AsciiBytes nameAlias) { + try { + long offset = this.centralDirectoryOffsets.get(index); + FileHeader cached = (FileHeader)this.entriesCache.get(index); + FileHeader entry = (FileHeader)(cached != null ? cached : CentralDirectoryFileHeader.fromRandomAccessData(this.centralDirectoryData, offset, this.filter)); + if (CentralDirectoryFileHeader.class.equals(entry.getClass()) && type.equals(JarEntry.class)) { + entry = new JarEntry(this.jarFile, index, (CentralDirectoryFileHeader)entry, nameAlias); + } + + if (cacheEntry && cached != entry) { + this.entriesCache.put(index, entry); + } + + return entry; + } catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + private int getFirstIndex(int hashCode) { + int index = Arrays.binarySearch(this.hashCodes, 0, this.size, hashCode); + if (index < 0) { + return -1; + } else { + while(index > 0 && this.hashCodes[index - 1] == hashCode) { + --index; + } + + return index; + } + } + + void clearCache() { + this.entriesCache.clear(); + } + + private AsciiBytes applyFilter(AsciiBytes name) { + return this.filter != null ? this.filter.apply(name) : name; + } + + JarEntryCertification getCertification(JarEntry entry) throws IOException { + JarEntryCertification[] certifications = this.certifications; + if (certifications == null) { + certifications = new JarEntryCertification[this.size]; + JarInputStream certifiedJarStream = new JarInputStream(this.jarFile.getData().getInputStream()); + Throwable var4 = null; + + try { + java.util.jar.JarEntry certifiedEntry = null; + + while((certifiedEntry = certifiedJarStream.getNextJarEntry()) != null) { + certifiedJarStream.closeEntry(); + int index = this.getEntryIndex(certifiedEntry.getName()); + if (index != -1) { + certifications[index] = JarEntryCertification.from(certifiedEntry); + } + } + } catch (Throwable var14) { + var4 = var14; + throw var14; + } finally { + if (certifiedJarStream != null) { + if (var4 != null) { + try { + certifiedJarStream.close(); + } catch (Throwable var13) { + var4.addSuppressed(var13); + } + } else { + certifiedJarStream.close(); + } + } + + } + + this.certifications = certifications; + } + + JarEntryCertification certification = certifications[entry.getIndex()]; + return certification != null ? certification : JarEntryCertification.NONE; + } + + private int getEntryIndex(CharSequence name) { + int hashCode = AsciiBytes.hashCode(name); + + for(int index = this.getFirstIndex(hashCode); index >= 0 && index < this.size && this.hashCodes[index] == hashCode; ++index) { + FileHeader candidate = this.getEntry(index, FileHeader.class, false, (AsciiBytes)null); + if (candidate.hasName(name, '\u0000')) { + return index; + } + } + + return -1; + } + + private static void swap(int[] array, int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + private static void swap(long[] array, int i, int j) { + long temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + static { + int version; + try { + Object runtimeVersion = Runtime.class.getMethod("version").invoke((Object)null); + version = (Integer)runtimeVersion.getClass().getMethod("major").invoke(runtimeVersion); + } catch (Throwable var2) { + version = 8; + } + + RUNTIME_VERSION = version; + } + + private final class EntryIterator implements Iterator { + private final Runnable validator; + private int index; + + private EntryIterator(Runnable validator) { + this.index = 0; + this.validator = validator; + validator.run(); + } + + public boolean hasNext() { + this.validator.run(); + return this.index < JarFileEntries.this.size; + } + + public JarEntry next() { + this.validator.run(); + if (!this.hasNext()) { + throw new NoSuchElementException(); + } else { + int entryIndex = JarFileEntries.this.positions[this.index]; + ++this.index; + return (JarEntry)JarFileEntries.this.getEntry(entryIndex, JarEntry.class, false, (AsciiBytes)null); + } + } + } + + private interface Offsets { + void set(int index, long value); + + long get(int index); + + void swap(int i, int j); + + static Offsets from(CentralDirectoryEndRecord endRecord) { + int size = endRecord.getNumberOfRecords(); + return (Offsets)(endRecord.isZip64() ? new Zip64Offsets(size) : new ZipOffsets(size)); + } + } + + private static final class ZipOffsets implements Offsets { + private final int[] offsets; + + private ZipOffsets(int size) { + this.offsets = new int[size]; + } + + public void swap(int i, int j) { + JarFileEntries.swap(this.offsets, i, j); + } + + public void set(int index, long value) { + this.offsets[index] = (int)value; + } + + public long get(int index) { + return (long)this.offsets[index]; + } + } + + private static final class Zip64Offsets implements Offsets { + private final long[] offsets; + + private Zip64Offsets(int size) { + this.offsets = new long[size]; + } + + public void swap(int i, int j) { + JarFileEntries.swap(this.offsets, i, j); + } + + public void set(int index, long value) { + this.offsets[index] = value; + } + + public long get(int index) { + return this.offsets[index]; + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/JarFileWrapper.java b/src/main/java/org/springframework/boot/loader/jar/JarFileWrapper.java new file mode 100644 index 0000000..d30d9f5 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/JarFileWrapper.java @@ -0,0 +1,90 @@ +package org.springframework.boot.loader.jar; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.Permission; +import java.util.Enumeration; +import java.util.jar.Manifest; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; + +class JarFileWrapper extends AbstractJarFile { + private final JarFile parent; + + JarFileWrapper(JarFile parent) throws IOException { + super(parent.getRootJarFile().getFile()); + this.parent = parent; + if (System.getSecurityManager() == null) { + super.close(); + } + + } + + URL getUrl() throws MalformedURLException { + return this.parent.getUrl(); + } + + AbstractJarFile.JarFileType getType() { + return this.parent.getType(); + } + + Permission getPermission() { + return this.parent.getPermission(); + } + + public Manifest getManifest() throws IOException { + return this.parent.getManifest(); + } + + public Enumeration entries() { + return this.parent.entries(); + } + + public Stream stream() { + return this.parent.stream(); + } + + public java.util.jar.JarEntry getJarEntry(String name) { + return this.parent.getJarEntry(name); + } + + public ZipEntry getEntry(String name) { + return this.parent.getEntry(name); + } + + InputStream getInputStream() throws IOException { + return this.parent.getInputStream(); + } + + public synchronized InputStream getInputStream(ZipEntry ze) throws IOException { + return this.parent.getInputStream(ze); + } + + public String getComment() { + return this.parent.getComment(); + } + + public int size() { + return this.parent.size(); + } + + public String toString() { + return this.parent.toString(); + } + + public String getName() { + return this.parent.getName(); + } + + static JarFile unwrap(java.util.jar.JarFile jarFile) { + if (jarFile instanceof JarFile) { + return (JarFile)jarFile; + } else if (jarFile instanceof JarFileWrapper) { + return unwrap(((JarFileWrapper)jarFile).parent); + } else { + throw new IllegalStateException("Not a JarFile or Wrapper"); + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java b/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java new file mode 100644 index 0000000..d502370 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/JarURLConnection.java @@ -0,0 +1,334 @@ +package org.springframework.boot.loader.jar; + +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.net.URLStreamHandler; +import java.security.Permission; + +final class JarURLConnection extends java.net.JarURLConnection { + private static ThreadLocal useFastExceptions = new ThreadLocal(); + private static final FileNotFoundException FILE_NOT_FOUND_EXCEPTION = new FileNotFoundException("Jar file or entry not found"); + private static final IllegalStateException NOT_FOUND_CONNECTION_EXCEPTION; + private static final String SEPARATOR = "!/"; + private static final URL EMPTY_JAR_URL; + private static final JarEntryName EMPTY_JAR_ENTRY_NAME; + private static final JarURLConnection NOT_FOUND_CONNECTION; + private final AbstractJarFile jarFile; + private Permission permission; + private URL jarFileUrl; + private final JarEntryName jarEntryName; + private java.util.jar.JarEntry jarEntry; + + private JarURLConnection(URL url, AbstractJarFile jarFile, JarEntryName jarEntryName) throws IOException { + super(EMPTY_JAR_URL); + this.url = url; + this.jarFile = jarFile; + this.jarEntryName = jarEntryName; + } + + public void connect() throws IOException { + if (this.jarFile == null) { + throw FILE_NOT_FOUND_EXCEPTION; + } else { + if (!this.jarEntryName.isEmpty() && this.jarEntry == null) { + this.jarEntry = this.jarFile.getJarEntry(this.getEntryName()); + if (this.jarEntry == null) { + this.throwFileNotFound(this.jarEntryName, this.jarFile); + } + } + + this.connected = true; + } + } + + public java.util.jar.JarFile getJarFile() throws IOException { + this.connect(); + return this.jarFile; + } + + public URL getJarFileURL() { + if (this.jarFile == null) { + throw NOT_FOUND_CONNECTION_EXCEPTION; + } else { + if (this.jarFileUrl == null) { + this.jarFileUrl = this.buildJarFileUrl(); + } + + return this.jarFileUrl; + } + } + + private URL buildJarFileUrl() { + try { + String spec = this.jarFile.getUrl().getFile(); + if (spec.endsWith("!/")) { + spec = spec.substring(0, spec.length() - "!/".length()); + } + + return !spec.contains("!/") ? new URL(spec) : new URL("jar:" + spec); + } catch (MalformedURLException ex) { + throw new IllegalStateException(ex); + } + } + + public java.util.jar.JarEntry getJarEntry() throws IOException { + if (this.jarEntryName != null && !this.jarEntryName.isEmpty()) { + this.connect(); + return this.jarEntry; + } else { + return null; + } + } + + public String getEntryName() { + if (this.jarFile == null) { + throw NOT_FOUND_CONNECTION_EXCEPTION; + } else { + return this.jarEntryName.toString(); + } + } + + public InputStream getInputStream() throws IOException { + if (this.jarFile == null) { + throw FILE_NOT_FOUND_EXCEPTION; + } else if (this.jarEntryName.isEmpty() && this.jarFile.getType() == AbstractJarFile.JarFileType.DIRECT) { + throw new IOException("no entry name specified"); + } else { + this.connect(); + InputStream inputStream = this.jarEntryName.isEmpty() ? this.jarFile.getInputStream() : this.jarFile.getInputStream(this.jarEntry); + if (inputStream == null) { + this.throwFileNotFound(this.jarEntryName, this.jarFile); + } + + return inputStream; + } + } + + private void throwFileNotFound(Object entry, AbstractJarFile jarFile) throws FileNotFoundException { + if (Boolean.TRUE.equals(useFastExceptions.get())) { + throw FILE_NOT_FOUND_EXCEPTION; + } else { + throw new FileNotFoundException("JAR entry " + entry + " not found in " + jarFile.getName()); + } + } + + public int getContentLength() { + long length = this.getContentLengthLong(); + return length > 2147483647L ? -1 : (int)length; + } + + public long getContentLengthLong() { + if (this.jarFile == null) { + return -1L; + } else { + try { + if (this.jarEntryName.isEmpty()) { + return (long)this.jarFile.size(); + } else { + java.util.jar.JarEntry entry = this.getJarEntry(); + return entry != null ? (long)((int)entry.getSize()) : -1L; + } + } catch (IOException var2) { + return -1L; + } + } + } + + public Object getContent() throws IOException { + this.connect(); + return this.jarEntryName.isEmpty() ? this.jarFile : super.getContent(); + } + + public String getContentType() { + return this.jarEntryName != null ? this.jarEntryName.getContentType() : null; + } + + public Permission getPermission() throws IOException { + if (this.jarFile == null) { + throw FILE_NOT_FOUND_EXCEPTION; + } else { + if (this.permission == null) { + this.permission = this.jarFile.getPermission(); + } + + return this.permission; + } + } + + public long getLastModified() { + if (this.jarFile != null && !this.jarEntryName.isEmpty()) { + try { + java.util.jar.JarEntry entry = this.getJarEntry(); + return entry != null ? entry.getTime() : 0L; + } catch (IOException var2) { + return 0L; + } + } else { + return 0L; + } + } + + static void setUseFastExceptions(boolean useFastExceptions) { + JarURLConnection.useFastExceptions.set(useFastExceptions); + } + + static JarURLConnection get(URL url, JarFile jarFile) throws IOException { + StringSequence spec = new StringSequence(url.getFile()); + int index = indexOfRootSpec(spec, jarFile.getPathFromRoot()); + if (index == -1) { + return Boolean.TRUE.equals(useFastExceptions.get()) ? NOT_FOUND_CONNECTION : new JarURLConnection(url, (AbstractJarFile)null, EMPTY_JAR_ENTRY_NAME); + } else { + int separator; + while((separator = spec.indexOf("!/", index)) > 0) { + JarEntryName entryName = JarURLConnection.JarEntryName.get(spec.subSequence(index, separator)); + JarEntry jarEntry = jarFile.getJarEntry(entryName.toCharSequence()); + if (jarEntry == null) { + return notFound(jarFile, entryName); + } + + jarFile = jarFile.getNestedJarFile(jarEntry); + index = separator + "!/".length(); + } + + JarEntryName jarEntryName = JarURLConnection.JarEntryName.get(spec, index); + if (Boolean.TRUE.equals(useFastExceptions.get()) && !jarEntryName.isEmpty() && !jarFile.containsEntry(jarEntryName.toString())) { + return NOT_FOUND_CONNECTION; + } else { + return new JarURLConnection(url, jarFile.getWrapper(), jarEntryName); + } + } + } + + private static int indexOfRootSpec(StringSequence file, String pathFromRoot) { + int separatorIndex = file.indexOf("!/"); + return separatorIndex >= 0 && file.startsWith(pathFromRoot, separatorIndex) ? separatorIndex + "!/".length() + pathFromRoot.length() : -1; + } + + private static JarURLConnection notFound() { + try { + return notFound((JarFile)null, (JarEntryName)null); + } catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + + private static JarURLConnection notFound(JarFile jarFile, JarEntryName jarEntryName) throws IOException { + return Boolean.TRUE.equals(useFastExceptions.get()) ? NOT_FOUND_CONNECTION : new JarURLConnection((URL)null, jarFile, jarEntryName); + } + + static { + NOT_FOUND_CONNECTION_EXCEPTION = new IllegalStateException(FILE_NOT_FOUND_EXCEPTION); + + try { + EMPTY_JAR_URL = new URL("jar:", (String)null, 0, "file:!/", new URLStreamHandler() { + protected URLConnection openConnection(URL u) throws IOException { + return null; + } + }); + } catch (MalformedURLException ex) { + throw new IllegalStateException(ex); + } + + EMPTY_JAR_ENTRY_NAME = new JarEntryName(new StringSequence("")); + NOT_FOUND_CONNECTION = notFound(); + } + + static class JarEntryName { + private final StringSequence name; + private String contentType; + + JarEntryName(StringSequence spec) { + this.name = this.decode(spec); + } + + private StringSequence decode(StringSequence source) { + if (!source.isEmpty() && source.indexOf('%') >= 0) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(source.length()); + this.write(source.toString(), bos); + return new StringSequence(AsciiBytes.toString(bos.toByteArray())); + } else { + return source; + } + } + + private void write(String source, ByteArrayOutputStream outputStream) { + int length = source.length(); + + for(int i = 0; i < length; ++i) { + int c = source.charAt(i); + if (c > 127) { + try { + String encoded = URLEncoder.encode(String.valueOf((char)c), "UTF-8"); + this.write(encoded, outputStream); + } catch (UnsupportedEncodingException ex) { + throw new IllegalStateException(ex); + } + } else { + if (c == 37) { + if (i + 2 >= length) { + throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); + } + + c = this.decodeEscapeSequence(source, i); + i += 2; + } + + outputStream.write(c); + } + } + + } + + private char decodeEscapeSequence(String source, int i) { + int hi = Character.digit(source.charAt(i + 1), 16); + int lo = Character.digit(source.charAt(i + 2), 16); + if (hi != -1 && lo != -1) { + return (char)((hi << 4) + lo); + } else { + throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); + } + } + + CharSequence toCharSequence() { + return this.name; + } + + public String toString() { + return this.name.toString(); + } + + boolean isEmpty() { + return this.name.isEmpty(); + } + + String getContentType() { + if (this.contentType == null) { + this.contentType = this.deduceContentType(); + } + + return this.contentType; + } + + private String deduceContentType() { + String type = this.isEmpty() ? "x-java/jar" : null; + type = type != null ? type : URLConnection.guessContentTypeFromName(this.toString()); + type = type != null ? type : "content/unknown"; + return type; + } + + static JarEntryName get(StringSequence spec) { + return get(spec, 0); + } + + static JarEntryName get(StringSequence spec, int beginIndex) { + return spec.length() <= beginIndex ? JarURLConnection.EMPTY_JAR_ENTRY_NAME : new JarEntryName(spec.subSequence(beginIndex)); + } + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/StringSequence.java b/src/main/java/org/springframework/boot/loader/jar/StringSequence.java new file mode 100644 index 0000000..c36f2c8 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/StringSequence.java @@ -0,0 +1,116 @@ +package org.springframework.boot.loader.jar; + +import java.util.Objects; + +final class StringSequence implements CharSequence { + private final String source; + private final int start; + private final int end; + private int hash; + + StringSequence(String source) { + this(source, 0, source != null ? source.length() : -1); + } + + StringSequence(String source, int start, int end) { + Objects.requireNonNull(source, "Source must not be null"); + if (start < 0) { + throw new StringIndexOutOfBoundsException(start); + } else if (end > source.length()) { + throw new StringIndexOutOfBoundsException(end); + } else { + this.source = source; + this.start = start; + this.end = end; + } + } + + StringSequence subSequence(int start) { + return this.subSequence(start, this.length()); + } + + public StringSequence subSequence(int start, int end) { + int subSequenceStart = this.start + start; + int subSequenceEnd = this.start + end; + if (subSequenceStart > this.end) { + throw new StringIndexOutOfBoundsException(start); + } else if (subSequenceEnd > this.end) { + throw new StringIndexOutOfBoundsException(end); + } else { + return start == 0 && subSequenceEnd == this.end ? this : new StringSequence(this.source, subSequenceStart, subSequenceEnd); + } + } + + public boolean isEmpty() { + return this.length() == 0; + } + + public int length() { + return this.end - this.start; + } + + public char charAt(int index) { + return this.source.charAt(this.start + index); + } + + int indexOf(char ch) { + return this.source.indexOf(ch, this.start) - this.start; + } + + int indexOf(String str) { + return this.source.indexOf(str, this.start) - this.start; + } + + int indexOf(String str, int fromIndex) { + return this.source.indexOf(str, this.start + fromIndex) - this.start; + } + + boolean startsWith(String prefix) { + return this.startsWith(prefix, 0); + } + + boolean startsWith(String prefix, int offset) { + int prefixLength = prefix.length(); + int length = this.length(); + return length - prefixLength - offset < 0 ? false : this.source.startsWith(prefix, this.start + offset); + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!(obj instanceof CharSequence)) { + return false; + } else { + CharSequence other = (CharSequence)obj; + int n = this.length(); + if (n != other.length()) { + return false; + } else { + for(int i = 0; n-- != 0; ++i) { + if (this.charAt(i) != other.charAt(i)) { + return false; + } + } + + return true; + } + } + } + + public int hashCode() { + int hash = this.hash; + if (hash == 0 && this.length() > 0) { + for(int i = this.start; i < this.end; ++i) { + hash = 31 * hash + this.source.charAt(i); + } + + this.hash = hash; + } + + return hash; + } + + public String toString() { + return this.source.substring(this.start, this.end); + } +} diff --git a/src/main/java/org/springframework/boot/loader/jar/ZipInflaterInputStream.java b/src/main/java/org/springframework/boot/loader/jar/ZipInflaterInputStream.java new file mode 100644 index 0000000..22d75ef --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jar/ZipInflaterInputStream.java @@ -0,0 +1,58 @@ +package org.springframework.boot.loader.jar; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + +class ZipInflaterInputStream extends InflaterInputStream { + private int available; + private boolean extraBytesWritten; + + ZipInflaterInputStream(InputStream inputStream, int size) { + super(inputStream, new Inflater(true), getInflaterBufferSize((long)size)); + this.available = size; + } + + public int available() throws IOException { + return this.available < 0 ? super.available() : this.available; + } + + public int read(byte[] b, int off, int len) throws IOException { + int result = super.read(b, off, len); + if (result != -1) { + this.available -= result; + } + + return result; + } + + public void close() throws IOException { + super.close(); + this.inf.end(); + } + + protected void fill() throws IOException { + try { + super.fill(); + } catch (EOFException ex) { + if (this.extraBytesWritten) { + throw ex; + } + + this.len = 1; + this.buf[0] = 0; + this.extraBytesWritten = true; + this.inf.setInput(this.buf, 0, this.len); + } + + } + + private static int getInflaterBufferSize(long size) { + size += 2L; + size = size > 65536L ? 8192L : size; + size = size <= 0L ? 4096L : size; + return (int)size; + } +} diff --git a/src/main/java/org/springframework/boot/loader/jarmode/JarMode.java b/src/main/java/org/springframework/boot/loader/jarmode/JarMode.java new file mode 100644 index 0000000..08db2b2 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jarmode/JarMode.java @@ -0,0 +1,7 @@ +package org.springframework.boot.loader.jarmode; + +public interface JarMode { + boolean accepts(String mode); + + void run(String mode, String[] args); +} diff --git a/src/main/java/org/springframework/boot/loader/jarmode/JarModeLauncher.java b/src/main/java/org/springframework/boot/loader/jarmode/JarModeLauncher.java new file mode 100644 index 0000000..64a80a9 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jarmode/JarModeLauncher.java @@ -0,0 +1,28 @@ +package org.springframework.boot.loader.jarmode; + +import org.springframework.core.io.support.SpringFactoriesLoader; +import org.springframework.util.ClassUtils; + +public final class JarModeLauncher { + static final String DISABLE_SYSTEM_EXIT = JarModeLauncher.class.getName() + ".DISABLE_SYSTEM_EXIT"; + + private JarModeLauncher() { + } + + public static void main(String[] args) { + String mode = System.getProperty("jarmode"); + + for(JarMode candidate : SpringFactoriesLoader.loadFactories(JarMode.class, ClassUtils.getDefaultClassLoader())) { + if (candidate.accepts(mode)) { + candidate.run(mode, args); + return; + } + } + + System.err.println("Unsupported jarmode '" + mode + "'"); + if (!Boolean.getBoolean(DISABLE_SYSTEM_EXIT)) { + System.exit(1); + } + + } +} diff --git a/src/main/java/org/springframework/boot/loader/jarmode/TestJarMode.java b/src/main/java/org/springframework/boot/loader/jarmode/TestJarMode.java new file mode 100644 index 0000000..32342f5 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/jarmode/TestJarMode.java @@ -0,0 +1,13 @@ +package org.springframework.boot.loader.jarmode; + +import java.util.Arrays; + +class TestJarMode implements JarMode { + public boolean accepts(String mode) { + return "test".equals(mode); + } + + public void run(String mode, String[] args) { + System.out.println("running in " + mode + " jar mode " + Arrays.asList(args)); + } +} diff --git a/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java b/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java new file mode 100644 index 0000000..75d3fc9 --- /dev/null +++ b/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java @@ -0,0 +1,143 @@ +package org.springframework.boot.loader.util; + +import java.util.HashSet; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; + +public abstract class SystemPropertyUtils { + public static final String PLACEHOLDER_PREFIX = "${"; + public static final String PLACEHOLDER_SUFFIX = "}"; + public static final String VALUE_SEPARATOR = ":"; + private static final String SIMPLE_PREFIX = "${".substring(1); + + public static String resolvePlaceholders(String text) { + return text == null ? text : parseStringValue((Properties)null, text, text, new HashSet()); + } + + public static String resolvePlaceholders(Properties properties, String text) { + return text == null ? text : parseStringValue(properties, text, text, new HashSet()); + } + + private static String parseStringValue(Properties properties, String value, String current, Set visitedPlaceholders) { + StringBuilder buf = new StringBuilder(current); + int startIndex = current.indexOf("${"); + + while(startIndex != -1) { + int endIndex = findPlaceholderEndIndex(buf, startIndex); + if (endIndex != -1) { + String placeholder = buf.substring(startIndex + "${".length(), endIndex); + String originalPlaceholder = placeholder; + if (!visitedPlaceholders.add(placeholder)) { + throw new IllegalArgumentException("Circular placeholder reference '" + placeholder + "' in property definitions"); + } + + placeholder = parseStringValue(properties, value, placeholder, visitedPlaceholders); + String propVal = resolvePlaceholder(properties, value, placeholder); + if (propVal == null) { + int separatorIndex = placeholder.indexOf(":"); + if (separatorIndex != -1) { + String actualPlaceholder = placeholder.substring(0, separatorIndex); + String defaultValue = placeholder.substring(separatorIndex + ":".length()); + propVal = resolvePlaceholder(properties, value, actualPlaceholder); + if (propVal == null) { + propVal = defaultValue; + } + } + } + + if (propVal != null) { + propVal = parseStringValue(properties, value, propVal, visitedPlaceholders); + buf.replace(startIndex, endIndex + "}".length(), propVal); + startIndex = buf.indexOf("${", startIndex + propVal.length()); + } else { + startIndex = buf.indexOf("${", endIndex + "}".length()); + } + + visitedPlaceholders.remove(originalPlaceholder); + } else { + startIndex = -1; + } + } + + return buf.toString(); + } + + private static String resolvePlaceholder(Properties properties, String text, String placeholderName) { + String propVal = getProperty(placeholderName, (String)null, text); + if (propVal != null) { + return propVal; + } else { + return properties != null ? properties.getProperty(placeholderName) : null; + } + } + + public static String getProperty(String key) { + return getProperty(key, (String)null, ""); + } + + public static String getProperty(String key, String defaultValue) { + return getProperty(key, defaultValue, ""); + } + + public static String getProperty(String key, String defaultValue, String text) { + try { + String propVal = System.getProperty(key); + if (propVal == null) { + propVal = System.getenv(key); + } + + if (propVal == null) { + String name = key.replace('.', '_'); + propVal = System.getenv(name); + } + + if (propVal == null) { + String name = key.toUpperCase(Locale.ENGLISH).replace('.', '_'); + propVal = System.getenv(name); + } + + if (propVal != null) { + return propVal; + } + } catch (Throwable ex) { + System.err.println("Could not resolve key '" + key + "' in '" + text + "' as system property or in environment: " + ex); + } + + return defaultValue; + } + + private static int findPlaceholderEndIndex(CharSequence buf, int startIndex) { + int index = startIndex + "${".length(); + int withinNestedPlaceholder = 0; + + while(index < buf.length()) { + if (substringMatch(buf, index, "}")) { + if (withinNestedPlaceholder <= 0) { + return index; + } + + --withinNestedPlaceholder; + index += "}".length(); + } else if (substringMatch(buf, index, SIMPLE_PREFIX)) { + ++withinNestedPlaceholder; + index += SIMPLE_PREFIX.length(); + } else { + ++index; + } + } + + return -1; + } + + private static boolean substringMatch(CharSequence str, int index, CharSequence substring) { + for(int j = 0; j < substring.length(); ++j) { + int i = index + j; + if (i >= str.length() || str.charAt(i) != substring.charAt(j)) { + return false; + } + } + + return true; + } +} diff --git a/src/main/resources/META-INF/build-info.properties b/src/main/resources/META-INF/build-info.properties new file mode 100644 index 0000000..e020fa8 --- /dev/null +++ b/src/main/resources/META-INF/build-info.properties @@ -0,0 +1,5 @@ +build.artifact=midm +build.group=com.mitac +build.name=MiDM +build.time=2025-02-21T08\:13\:58.694953Z +build.version=1.1.1.12 diff --git a/src/main/resources/apksigner/apksigner.jar b/src/main/resources/apksigner/apksigner.jar new file mode 100644 index 0000000..65746fa Binary files /dev/null and b/src/main/resources/apksigner/apksigner.jar differ diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..8e4ed91 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,10 @@ +logging.level.com.midm=TRACE +logging.level.org.springframework.data.convert.CustomConversions=ERROR +logging.level.root=WARN +server.servlet.session.cookie.http-only=true +server.servlet.session.cookie.secure=true +server.tomcat.accesslog.directory= +server.tomcat.accesslog.enabled=true +spring.mvc.pathmatch.matching-strategy=ant-path-matcher +spring.thymeleaf.cache=true +spring.web.resources.cache.cachecontrol.max-age=2592000 diff --git a/src/main/resources/help/app.releaseNote.html b/src/main/resources/help/app.releaseNote.html new file mode 100644 index 0000000..4086679 --- /dev/null +++ b/src/main/resources/help/app.releaseNote.html @@ -0,0 +1,77 @@ + + + + MiDM Release Note + + + + + +
+

[(${app.title["en-US"]})] release note with [(${keyStore})] key

+

[(${app.title["en-US"]})] release note

+
+ + +
+ + + Select your platform key + +
+
+ +
+ + +
+

+ + [(${note.versionName})]([(${note.getVersionCode()})]) + + : [(${#dates.format(note.releasedAt, 'yyyy-MM-dd')})] + ★ +

+

+ [(${note.versionName})]([(${note.getVersionCode()})]) : [(${#dates.format(note.releasedAt, 'yyyy-MM-dd')})] +

+ +
+
New functions
+
    +
  • +
+
+ +
+
Bug fixes and improvements
+
    +
  • +
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/help/helpMessage.html b/src/main/resources/help/helpMessage.html new file mode 100644 index 0000000..d69885d --- /dev/null +++ b/src/main/resources/help/helpMessage.html @@ -0,0 +1,17 @@ + + +
[(${description})]
+ +
+
+ + +
+ + + + + +
+
+
diff --git a/src/main/resources/help/profileProgress.html b/src/main/resources/help/profileProgress.html new file mode 100644 index 0000000..10a6b67 --- /dev/null +++ b/src/main/resources/help/profileProgress.html @@ -0,0 +1,53 @@ + + + + + + + +
+ Applied + + [(${progress.applied})] +
+ + + + + + +
+
Apps
+
+ [( ${progress.apps.progress.installed})]/[(${progress.apps.progress.total} )]([( ${#numbers.formatPercent(progress.apps.progress.percent, 0, 1)} )]) +
+ + + + + +
+
+ + + + + + +
+
System image
+
+ +
+ + + + + + + + + +
+
+ \ No newline at end of file diff --git a/src/main/resources/help/webapp.releaseNote.html b/src/main/resources/help/webapp.releaseNote.html new file mode 100644 index 0000000..71af3d5 --- /dev/null +++ b/src/main/resources/help/webapp.releaseNote.html @@ -0,0 +1,46 @@ + + + + MiDM host Release Note + + + +
+

+
+ + +
+ +

+ + + [(${app.appInfo.version})] + + : [(${#dates.format(app.appInfo.buildTime, 'yyyy-MM-dd')})] + ★ +

+ +
    +
    +
    New functions
    +
      +
    • +
    +
    + +
    +
    Bug fixes and improvements
    +
      +
    • +
    +
    +
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/mail/account.login.failure.html b/src/main/resources/mail/account.login.failure.html new file mode 100644 index 0000000..a6acf1d --- /dev/null +++ b/src/main/resources/mail/account.login.failure.html @@ -0,0 +1,36 @@ + + + +
+

MiDM Service

+
+

Dear

+

+ Your account has been blocked to login due to exceed number of maximum login failure. + You will be able to try to login after[(${retryAfter})]. + If it is not from you but you need to login now, you may reset your password. +

+

+ Email account: [(${user.getEmail()})]
+ IP address: [(${remoteIp})]
+ OS: [(${client.os.family})]
+ Browser: [(${client.userAgent.family})] +

+

+ + + Login + + +

+

+ If you have trouble to login, please contact service manager. +

+

+ Thank you for sign in MiDM!
+ - MiDM Support Team +

+
+
+ + diff --git a/src/main/resources/mail/accountActivated.html b/src/main/resources/mail/accountActivated.html new file mode 100644 index 0000000..236f223 --- /dev/null +++ b/src/main/resources/mail/accountActivated.html @@ -0,0 +1,34 @@ + + + +
+

MiDM Service

+
+

Hello

+

+ You account has been activated. You are now ready to login. +

+

+ Your email account is : [(${user.getEmail()})] +

+

+ Your password is : [(${user.getPassword()})] +

+

+ + + Login + + +

+

+ If you have trouble to login, please contact service manager. +

+

+ Thank you for sign in MiDM!
+ - MiDM Support Team +

+
+
+ + diff --git a/src/main/resources/mail/activateAccount.html b/src/main/resources/mail/activateAccount.html new file mode 100644 index 0000000..fc653fe --- /dev/null +++ b/src/main/resources/mail/activateAccount.html @@ -0,0 +1,29 @@ + + + +
+

MiDM Service

+
+

Hello [(${user.getName()})]

+

+ You are one step away from fully activating your MiDM account! +

+

+ Your password is : [(${user.getPassword()})] +

+

+ + + Activate account + + +

+

Account will be activated immediately.

+

+ Thank you for sign in MiDM!
+ - MiDM Support Team +

+
+
+ + diff --git a/src/main/resources/mail/confirmAccount.html b/src/main/resources/mail/confirmAccount.html new file mode 100644 index 0000000..6fb8818 --- /dev/null +++ b/src/main/resources/mail/confirmAccount.html @@ -0,0 +1,28 @@ + + + +
+

MiDM Service

+
+

Hello

+

+ It'll be confirmed your registration by pressing confirm account button. +

+

+ + + Confirm account + + +

+

+ Your account will be activated after review this record. Once administrator activate your account, you will have activation mail. +

+

+ Thank you for sign in MiDM!
+ - MiDM Support Team +

+
+
+ + diff --git a/src/main/resources/mail/host.license.html b/src/main/resources/mail/host.license.html new file mode 100644 index 0000000..1dc034d --- /dev/null +++ b/src/main/resources/mail/host.license.html @@ -0,0 +1,48 @@ +
+ + + + + + + + + + + + +
+

Standalone [(${news.forWhat})]

+
+

Dear MiDM User:

+

Host License is ready. Please login to site [(${news.reference.siteIdName})] to get the license key

+
+ + + + + + + + + + + + + + + + + + + +
Site: [(${news.reference.siteIdName})]
License Type: [(${news.reference.licenseType})]
Valid To: [(${news.reference.validTo})]
Device limitation: [(${news.reference.deviceLimit})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/host.license.request.html b/src/main/resources/mail/host.license.request.html new file mode 100644 index 0000000..56533ad --- /dev/null +++ b/src/main/resources/mail/host.license.request.html @@ -0,0 +1,52 @@ +
+ + + + + + + + + + + + +
+

Standalone [(${news.forWhat})]

+
+

Hello MiDM site manager:

+

Host License has been requested by [(${news.reference.siteIdName})], please check following information and contact them asap.

+
+ + + + + + + + + + + + + + + + + + + + + + + +
Site: [(${news.reference.siteIdName})]
License Type: [(${news.reference.licenseType})]
Valid To: [(${news.reference.validTo})]
Period: [(${news.reference.period})] years
Device limitation: [(${news.reference.deviceLimit})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
diff --git a/src/main/resources/mail/noti.batteryCondition.abnormal.html b/src/main/resources/mail/noti.batteryCondition.abnormal.html new file mode 100644 index 0000000..cc633f3 --- /dev/null +++ b/src/main/resources/mail/noti.batteryCondition.abnormal.html @@ -0,0 +1,58 @@ +
+ + + + + + + + + + + + +
+

Battery ([(${batterySerial})]) has reported abnormal conditions. Service soon.

+
+

Dear MiDM User :

+

A battery has been reported to have experienced abnormal conditions and should be serviced soon.

+ +
+ + + + + + + + + + + + + + + + + + + + + + +
Site: [(${siteName})]
Battery S/NDevice S/NDevice ModelDevice Group
[(${batterySerial})][(${deviceSerial})][(${model})][(${deviceGroupName})]
+
+ +

+ Important:
+ It is recommended to service device batteries that experienced abnormal conditions to prevent possible device malfunction overtime. +

+ +

+ Kind regards,
+ MiDM service support. +

+
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/noti.install.failed.html b/src/main/resources/mail/noti.install.failed.html new file mode 100644 index 0000000..518842e --- /dev/null +++ b/src/main/resources/mail/noti.install.failed.html @@ -0,0 +1,31 @@ +
+ + + + + + + + + + + + +
+

Install failure

+
+

Dear SuperVisors :

+

Device failed to download the following:

+ . Installer type : [(${category})]
+ . File UUID : [(${fileUuid})]
+ . File Name : [(${fileName})]
+ . Fail reaseon : [(${reason})]
+ . Serial No : [(${ssn})] +

+ Kind regards,
+ MiDM service support. +

+
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/noti.license.html b/src/main/resources/mail/noti.license.html new file mode 100644 index 0000000..023093e --- /dev/null +++ b/src/main/resources/mail/noti.license.html @@ -0,0 +1,56 @@ +
+ + + + + + + + + + + + +
+

MiDM Device License Expiring Notice

+
+

Dear MiDM User:

+

     There're [(${expiring.subTotal})] device licenses that are due to expire.
+ Once a license has expired and no auto-renew policy has been enabled on these devices, you will no longer be able to manage them from the MiDM Console until you have assigned a new license manually.
+      Please check your license status. If you are using the auto-renew feature, make sure you have enough available licences of the same type and duration in your license inventory for MiDM to handle the renewal automatically. +

+
+ + + + + + + + + + + + + + + + + + + + +
Site [(${site.name})]([(${site.idName})])
Expired in 10 days[(${expiring.in10})]
Expired in 30 days[(${expiring.in10 +expiring.in30})]
Expired in 45 days[(${expiring.in10 +expiring.in30 +expiring.in45})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+ +
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/noti.request.pullFile.html b/src/main/resources/mail/noti.request.pullFile.html new file mode 100644 index 0000000..44d038e --- /dev/null +++ b/src/main/resources/mail/noti.request.pullFile.html @@ -0,0 +1,44 @@ +
+ + + + + + + + + + + + +
+

File download from device [(${deviceSerial})]

+
+

Dear MiDM User:

+

Requested file is ready. Login to the site to get the download file. This will be expired at [(${news.reference.reportExpiry})]

+
+ + + + + + + + + + + + + + + +
Site: [(${news.reference.siteName})]
Device: [(${deviceSerial})]
File: [(${fileName})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/noti.support.general.html b/src/main/resources/mail/noti.support.general.html new file mode 100644 index 0000000..47f1934 --- /dev/null +++ b/src/main/resources/mail/noti.support.general.html @@ -0,0 +1,22 @@ +
+ + + + + + + + + + + + +
+

+
+

+ +
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/noti.support.maintenance.html b/src/main/resources/mail/noti.support.maintenance.html new file mode 100644 index 0000000..e8b518b --- /dev/null +++ b/src/main/resources/mail/noti.support.maintenance.html @@ -0,0 +1,44 @@ +
+ + + + + + + + + + + + +
+

MiDM Host Maintenance Notice

+
+

Dear MiDM User:

+

To improve MiDM service quality, we will perform maintenance host at following time.

+
+ + + + + + + + + + + +
From: [(${message.toDateString(message.message.start, "yyyy-MM-dd HH:mm z")})]
To: [(${message.toDateString(message.message.end, "yyyy-MM-dd HH:mm z")})]
+
+

During this time, MiDM service may be unavailable.
+ Please accept our sincere apologies for any inconveniences that this may cause.

+

+

+ Kind regards,
+ The MiDM Support Team. +

+ +
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/noti.support.urgent.html b/src/main/resources/mail/noti.support.urgent.html new file mode 100644 index 0000000..a484c72 --- /dev/null +++ b/src/main/resources/mail/noti.support.urgent.html @@ -0,0 +1,22 @@ +
+ + + + + + + + + + + + +
+

Urgent Notice: [(${message.getTitle()})]

+
+

+ +
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/passwordReset.html b/src/main/resources/mail/passwordReset.html new file mode 100644 index 0000000..f0fb699 --- /dev/null +++ b/src/main/resources/mail/passwordReset.html @@ -0,0 +1,38 @@ +
+ + + + + + + + + + + + +
+

Password reset

+
+

Hello

+

You have to reset the password in 30 minutes. No activity in 30 minutes, you have to request again to reset password.

+
+ + + + +
+ + Reset password + +
+
+

Press reset password button to continue. It'll open the password change page.

+

+ Kind regards,
+ The MiDM Support Team. +

+
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/qrRegister.html b/src/main/resources/mail/qrRegister.html new file mode 100644 index 0000000..93daa1e --- /dev/null +++ b/src/main/resources/mail/qrRegister.html @@ -0,0 +1,48 @@ + +
+ + + + + + + + + + + + +
+

MiDM QR code for device registration

+
+

Dear [(${site.profile.name})]([(${site.idName})]):

+

Read the QR code to register your device using MiDM Client app.

+
+ QR code +
+
+ To register the device: +
    +
  1. Start MiDM Client app.
  2. +
  3. Tap the camera button.
  4. +
  5. Read QR code.
  6. +
+ The device will be registered automatically if the device network is available. +
+
+

Cautions:

+
    +
  • The device will be registered to the site which is defined in this code.
  • +
  • If the device is registered to other site, it will be enrolled to the site.
  • +
  • Do not try with other barcode app.
  • +
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ © MiTAC Digital Technology. All Rights Reserved. +
+
+ \ No newline at end of file diff --git a/src/main/resources/mail/report.default.html b/src/main/resources/mail/report.default.html new file mode 100644 index 0000000..43193da --- /dev/null +++ b/src/main/resources/mail/report.default.html @@ -0,0 +1,40 @@ +
+ + + + + + + + + + + + +
+

MiDM Report for [(${news.forWhat})]

+
+

Dear MiDM User:

+

MiDM report is ready. Find the report attached or login to the site to get the report. This report will be expired at [(${news.reference.reportExpiry})]

+
+ + + + + + + + + + + +
Site: [(${news.reference.siteName})]
File: [(${fileName})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/sendNotification.html b/src/main/resources/mail/sendNotification.html new file mode 100644 index 0000000..2a2ebd0 --- /dev/null +++ b/src/main/resources/mail/sendNotification.html @@ -0,0 +1,37 @@ +
+ + + + + + + + + + + + +
+

MiDM notificagtion service

+
+

Hello

+

This message was sent from MiDM notification service.

+
+ + + + + + + +
Title
Content
+
+

Press reset password button to continue. It'll open the password change page.

+

+ Kind regards,
+ The MiDM Support Team. +

+
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/site.license.html b/src/main/resources/mail/site.license.html new file mode 100644 index 0000000..51b9760 --- /dev/null +++ b/src/main/resources/mail/site.license.html @@ -0,0 +1,48 @@ +
+ + + + + + + + + + + + +
+

[(${news.forWhat})]

+
+

Dear MiDM User:

+

Site License is ready. Please login to site [(${news.reference.siteIdName})] to check license detail

+
+ + + + + + + + + + + + + + + + + + + +
Site: [(${news.reference.siteIdName})]
License Model: [(${news.reference.licenseModel})]
Plan: [(${news.reference.plan})]
Amount: [(${news.reference.amount})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/site.license.request.html b/src/main/resources/mail/site.license.request.html new file mode 100644 index 0000000..d8c37bd --- /dev/null +++ b/src/main/resources/mail/site.license.request.html @@ -0,0 +1,48 @@ +
+ + + + + + + + + + + + +
+

[(${news.forWhat})]

+
+

Hello MiDM site manager:

+

Site License has been requested by [(${news.reference.siteIdName})], please check following information and contact them asap.

+
+ + + + + + + + + + + + + + + + + + + +
Site: [(${news.reference.siteIdName})]
License Model: [(${news.reference.licenseModel})]
Plan: [(${news.reference.plan})]
Amount: [(${news.reference.amount})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/site.upgrade.html b/src/main/resources/mail/site.upgrade.html new file mode 100644 index 0000000..0182a8f --- /dev/null +++ b/src/main/resources/mail/site.upgrade.html @@ -0,0 +1,32 @@ +
+ + + + + + + + + + + + +
+

[(${news.forWhat})]

+
+

Dear MiDM User:

+

Site has upgraded from [(${news.reference.plan})] to [(${news.reference.targetPlan})] successfully. Please login to site [(${news.reference.siteIdName})] to check more detail

+
+ + + +
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/site.upgrade.request.html b/src/main/resources/mail/site.upgrade.request.html new file mode 100644 index 0000000..e497801 --- /dev/null +++ b/src/main/resources/mail/site.upgrade.request.html @@ -0,0 +1,48 @@ +
+ + + + + + + + + + + + +
+

[(${news.forWhat})]

+
+

Hello MiDM site manager:

+

Site Upgrade has been requested by [(${news.reference.siteIdName})], please check following information and contact them asap.

+
+ + + + + + + + + + + + + + + + + + + +
Site: [(${news.reference.siteIdName})]
Plan: [(${news.reference.plan})]
Upgrade to: [(${news.reference.targetPlan})]
Request at: [(${news.reference.requestDate})]
+
+

+ Kind regards,
+ The MiDM Support Team. +

+
+ MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/siteRequest.html b/src/main/resources/mail/siteRequest.html new file mode 100644 index 0000000..c96f6f6 --- /dev/null +++ b/src/main/resources/mail/siteRequest.html @@ -0,0 +1,45 @@ + + + +
+

MiDM Service

+
+

Hello MiDM site manager.

+

+ requested free trial.
+ Please check following information and contact them asap. +

+
+ + + + + + + + + + + + + + + + + + + + + + +
Company name
Title
Name
Email
Phone
Country
Industry
+
+

+

+ Thank you for using MiDM!
+ - MiDM Host Service +

+
+
+ + diff --git a/src/main/resources/mail/standaloneMessage.html b/src/main/resources/mail/standaloneMessage.html new file mode 100644 index 0000000..d21b98f --- /dev/null +++ b/src/main/resources/mail/standaloneMessage.html @@ -0,0 +1,26 @@ + + + +
+

MiDM Service

+
+

Hello

+

+ This message was sent from MiDM notification service. +

+

+
+ + + + +
+
+

+ Thank you for sign in MiDM!
+ - MiDM Support Team +

+
+
+ + diff --git a/src/main/resources/mail/template.html b/src/main/resources/mail/template.html new file mode 100644 index 0000000..72408e0 --- /dev/null +++ b/src/main/resources/mail/template.html @@ -0,0 +1,42 @@ +
+ + + + + + + + + + + + +
+

MiDM Host Maintenance Notice

+
+

Dear MiDM User:

+

To improve MiDM service quality, we will perform maintenance host at following time.

+
+ + + + + + + + + + + +
From: 2020-12-05 23:00 UTC
To: 2020-12-06 00:00 UTC
+
+

During this time, MiDM service may be unavailable.
+ Please accept our sincere apologies for any inconveniences that this may cause.

+

+ Kind regards,
+ The MiDM Support Team. +

+
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/testMail.html b/src/main/resources/mail/testMail.html new file mode 100644 index 0000000..03517c7 --- /dev/null +++ b/src/main/resources/mail/testMail.html @@ -0,0 +1,26 @@ +
+ + + + + + + + + + + + +
+

MiDM service test mail

+
+

Dear MiDM customers:

+

If you got this mail, your email settings must be correct.

+

+ Kind regards,
+ MiDM service support. +

+
+ © MiTAC Digital Technology. All Rights Reserved. +
+
\ No newline at end of file diff --git a/src/main/resources/mail/welcome.html b/src/main/resources/mail/welcome.html new file mode 100644 index 0000000..d53b0d5 --- /dev/null +++ b/src/main/resources/mail/welcome.html @@ -0,0 +1,19 @@ + + + + Certificate + + + +

+ Hello, David! +

+

+ Thanks for signing up, your account has been activated. +

+

+ Regards,
+ Follow Me Familly +

+ + diff --git a/src/main/resources/report/devices.general.xlsx b/src/main/resources/report/devices.general.xlsx new file mode 100644 index 0000000..c92bddb Binary files /dev/null and b/src/main/resources/report/devices.general.xlsx differ diff --git a/src/main/resources/report/profiles.general.xlsx b/src/main/resources/report/profiles.general.xlsx new file mode 100644 index 0000000..2698cba Binary files /dev/null and b/src/main/resources/report/profiles.general.xlsx differ diff --git a/src/main/resources/report/site.general.xlsx b/src/main/resources/report/site.general.xlsx new file mode 100644 index 0000000..dc60cd0 Binary files /dev/null and b/src/main/resources/report/site.general.xlsx differ diff --git a/src/main/resources/static/fonts/glyphicons-halflings-regular.eot b/src/main/resources/static/fonts/glyphicons-halflings-regular.eot new file mode 100644 index 0000000..4a4ca86 Binary files /dev/null and b/src/main/resources/static/fonts/glyphicons-halflings-regular.eot differ diff --git a/src/main/resources/static/fonts/glyphicons-halflings-regular.svg b/src/main/resources/static/fonts/glyphicons-halflings-regular.svg new file mode 100644 index 0000000..25691af --- /dev/null +++ b/src/main/resources/static/fonts/glyphicons-halflings-regular.svg @@ -0,0 +1,229 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/glyphicons-halflings-regular.ttf b/src/main/resources/static/fonts/glyphicons-halflings-regular.ttf new file mode 100644 index 0000000..67fa00b Binary files /dev/null and b/src/main/resources/static/fonts/glyphicons-halflings-regular.ttf differ diff --git a/src/main/resources/static/fonts/glyphicons-halflings-regular.woff b/src/main/resources/static/fonts/glyphicons-halflings-regular.woff new file mode 100644 index 0000000..8c54182 Binary files /dev/null and b/src/main/resources/static/fonts/glyphicons-halflings-regular.woff differ diff --git a/src/main/resources/static/fonts/glyphicons-halflings-regular.woff2 b/src/main/resources/static/fonts/glyphicons-halflings-regular.woff2 new file mode 100644 index 0000000..8c54182 Binary files /dev/null and b/src/main/resources/static/fonts/glyphicons-halflings-regular.woff2 differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.eot b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.eot new file mode 100644 index 0000000..b73776e Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.eot differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.svg b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.svg new file mode 100644 index 0000000..43b5ed2 --- /dev/null +++ b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.svg @@ -0,0 +1,593 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.ttf b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.ttf new file mode 100644 index 0000000..1da7276 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.ttf differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.woff b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.woff new file mode 100644 index 0000000..0c69948 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Bold-webfont.woff differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.eot b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.eot new file mode 100644 index 0000000..072cdc4 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.eot differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.svg b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.svg new file mode 100644 index 0000000..db6a617 --- /dev/null +++ b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.svg @@ -0,0 +1,641 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.ttf b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.ttf new file mode 100644 index 0000000..3b2fea0 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.ttf differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.woff b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.woff new file mode 100644 index 0000000..cc534a3 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Light-webfont.woff differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.eot b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.eot new file mode 100644 index 0000000..f9ad995 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.eot differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.svg b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.svg new file mode 100644 index 0000000..4ce289d --- /dev/null +++ b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.svg @@ -0,0 +1,593 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.ttf b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.ttf new file mode 100644 index 0000000..8aa64d8 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.ttf differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.woff b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.woff new file mode 100644 index 0000000..cd810ef Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Medium-webfont.woff differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.eot b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.eot new file mode 100644 index 0000000..9b5e8e4 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.eot differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.svg b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.svg new file mode 100644 index 0000000..de7d77f --- /dev/null +++ b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.svg @@ -0,0 +1,621 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.ttf b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.ttf new file mode 100644 index 0000000..44dd78d Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.ttf differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.woff b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.woff new file mode 100644 index 0000000..bfa05d5 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Regular-webfont.woff differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.eot b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.eot new file mode 100644 index 0000000..2284a3b Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.eot differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.svg b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.svg new file mode 100644 index 0000000..7394e3d --- /dev/null +++ b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.svg @@ -0,0 +1,631 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.ttf b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.ttf new file mode 100644 index 0000000..18919f7 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.ttf differ diff --git a/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.woff b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.woff new file mode 100644 index 0000000..f10b831 Binary files /dev/null and b/src/main/resources/static/fonts/roboto/Roboto-Thin-webfont.woff differ diff --git a/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.eot b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.eot new file mode 100644 index 0000000..d3b1566 Binary files /dev/null and b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.eot differ diff --git a/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.svg b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.svg new file mode 100644 index 0000000..d825f28 --- /dev/null +++ b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.svg @@ -0,0 +1,241 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.ttf b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.ttf new file mode 100644 index 0000000..3ec3851 Binary files /dev/null and b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.ttf differ diff --git a/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.woff b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.woff new file mode 100644 index 0000000..5085681 Binary files /dev/null and b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.woff differ diff --git a/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.woff2 b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.woff2 new file mode 100644 index 0000000..334469d Binary files /dev/null and b/src/main/resources/static/fonts/shadowsintolight/shadowsintolight-webfont.woff2 differ diff --git a/src/main/resources/static/fonts/weather-icons/weather-icons.eot b/src/main/resources/static/fonts/weather-icons/weather-icons.eot new file mode 100644 index 0000000..d7aff29 Binary files /dev/null and b/src/main/resources/static/fonts/weather-icons/weather-icons.eot differ diff --git a/src/main/resources/static/fonts/weather-icons/weather-icons.svg b/src/main/resources/static/fonts/weather-icons/weather-icons.svg new file mode 100644 index 0000000..dab6616 --- /dev/null +++ b/src/main/resources/static/fonts/weather-icons/weather-icons.svg @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/fonts/weather-icons/weather-icons.ttf b/src/main/resources/static/fonts/weather-icons/weather-icons.ttf new file mode 100644 index 0000000..53eef3a Binary files /dev/null and b/src/main/resources/static/fonts/weather-icons/weather-icons.ttf differ diff --git a/src/main/resources/static/fonts/weather-icons/weather-icons.woff b/src/main/resources/static/fonts/weather-icons/weather-icons.woff new file mode 100644 index 0000000..ce6d6e9 Binary files /dev/null and b/src/main/resources/static/fonts/weather-icons/weather-icons.woff differ diff --git a/src/main/resources/static/image/battery/average.png b/src/main/resources/static/image/battery/average.png new file mode 100644 index 0000000..bdae2b6 Binary files /dev/null and b/src/main/resources/static/image/battery/average.png differ diff --git a/src/main/resources/static/image/battery/general_average.png b/src/main/resources/static/image/battery/general_average.png new file mode 100644 index 0000000..e70c6ff Binary files /dev/null and b/src/main/resources/static/image/battery/general_average.png differ diff --git a/src/main/resources/static/image/battery/general_good.png b/src/main/resources/static/image/battery/general_good.png new file mode 100644 index 0000000..01c470e Binary files /dev/null and b/src/main/resources/static/image/battery/general_good.png differ diff --git a/src/main/resources/static/image/battery/general_service_soon.png b/src/main/resources/static/image/battery/general_service_soon.png new file mode 100644 index 0000000..0302aab Binary files /dev/null and b/src/main/resources/static/image/battery/general_service_soon.png differ diff --git a/src/main/resources/static/image/battery/good.png b/src/main/resources/static/image/battery/good.png new file mode 100644 index 0000000..1f25049 Binary files /dev/null and b/src/main/resources/static/image/battery/good.png differ diff --git a/src/main/resources/static/image/battery/no_data.png b/src/main/resources/static/image/battery/no_data.png new file mode 100644 index 0000000..76e4131 Binary files /dev/null and b/src/main/resources/static/image/battery/no_data.png differ diff --git a/src/main/resources/static/image/battery/service_soon.png b/src/main/resources/static/image/battery/service_soon.png new file mode 100644 index 0000000..5b14e5a Binary files /dev/null and b/src/main/resources/static/image/battery/service_soon.png differ diff --git a/src/main/resources/static/image/bg/background.jpg b/src/main/resources/static/image/bg/background.jpg new file mode 100644 index 0000000..1981fc2 Binary files /dev/null and b/src/main/resources/static/image/bg/background.jpg differ diff --git a/src/main/resources/static/image/empty.png b/src/main/resources/static/image/empty.png new file mode 100644 index 0000000..eb3a7af Binary files /dev/null and b/src/main/resources/static/image/empty.png differ diff --git a/src/main/resources/static/image/favicon.png b/src/main/resources/static/image/favicon.png new file mode 100644 index 0000000..01fc9fb Binary files /dev/null and b/src/main/resources/static/image/favicon.png differ diff --git a/src/main/resources/static/image/favicon_release_note.png b/src/main/resources/static/image/favicon_release_note.png new file mode 100644 index 0000000..6932044 Binary files /dev/null and b/src/main/resources/static/image/favicon_release_note.png differ diff --git a/src/main/resources/static/image/flag/ad.png b/src/main/resources/static/image/flag/ad.png new file mode 100644 index 0000000..625ca84 Binary files /dev/null and b/src/main/resources/static/image/flag/ad.png differ diff --git a/src/main/resources/static/image/flag/ae.png b/src/main/resources/static/image/flag/ae.png new file mode 100644 index 0000000..ef3a1ec Binary files /dev/null and b/src/main/resources/static/image/flag/ae.png differ diff --git a/src/main/resources/static/image/flag/af.png b/src/main/resources/static/image/flag/af.png new file mode 100644 index 0000000..a4742e2 Binary files /dev/null and b/src/main/resources/static/image/flag/af.png differ diff --git a/src/main/resources/static/image/flag/ag.png b/src/main/resources/static/image/flag/ag.png new file mode 100644 index 0000000..556d550 Binary files /dev/null and b/src/main/resources/static/image/flag/ag.png differ diff --git a/src/main/resources/static/image/flag/ai.png b/src/main/resources/static/image/flag/ai.png new file mode 100644 index 0000000..74ed29d Binary files /dev/null and b/src/main/resources/static/image/flag/ai.png differ diff --git a/src/main/resources/static/image/flag/al.png b/src/main/resources/static/image/flag/al.png new file mode 100644 index 0000000..92354cb Binary files /dev/null and b/src/main/resources/static/image/flag/al.png differ diff --git a/src/main/resources/static/image/flag/am.png b/src/main/resources/static/image/flag/am.png new file mode 100644 index 0000000..344a2a8 Binary files /dev/null and b/src/main/resources/static/image/flag/am.png differ diff --git a/src/main/resources/static/image/flag/an.png b/src/main/resources/static/image/flag/an.png new file mode 100644 index 0000000..633e4b8 Binary files /dev/null and b/src/main/resources/static/image/flag/an.png differ diff --git a/src/main/resources/static/image/flag/ao.png b/src/main/resources/static/image/flag/ao.png new file mode 100644 index 0000000..d6bd64a Binary files /dev/null and b/src/main/resources/static/image/flag/ao.png differ diff --git a/src/main/resources/static/image/flag/ar.png b/src/main/resources/static/image/flag/ar.png new file mode 100644 index 0000000..e5ef8f1 Binary files /dev/null and b/src/main/resources/static/image/flag/ar.png differ diff --git a/src/main/resources/static/image/flag/as.png b/src/main/resources/static/image/flag/as.png new file mode 100644 index 0000000..32f30e4 Binary files /dev/null and b/src/main/resources/static/image/flag/as.png differ diff --git a/src/main/resources/static/image/flag/at.png b/src/main/resources/static/image/flag/at.png new file mode 100644 index 0000000..0f15f34 Binary files /dev/null and b/src/main/resources/static/image/flag/at.png differ diff --git a/src/main/resources/static/image/flag/au.png b/src/main/resources/static/image/flag/au.png new file mode 100644 index 0000000..a01389a Binary files /dev/null and b/src/main/resources/static/image/flag/au.png differ diff --git a/src/main/resources/static/image/flag/aw.png b/src/main/resources/static/image/flag/aw.png new file mode 100644 index 0000000..a3579c2 Binary files /dev/null and b/src/main/resources/static/image/flag/aw.png differ diff --git a/src/main/resources/static/image/flag/ax.png b/src/main/resources/static/image/flag/ax.png new file mode 100644 index 0000000..1eea80a Binary files /dev/null and b/src/main/resources/static/image/flag/ax.png differ diff --git a/src/main/resources/static/image/flag/az.png b/src/main/resources/static/image/flag/az.png new file mode 100644 index 0000000..4ee9fe5 Binary files /dev/null and b/src/main/resources/static/image/flag/az.png differ diff --git a/src/main/resources/static/image/flag/ba.png b/src/main/resources/static/image/flag/ba.png new file mode 100644 index 0000000..c774992 Binary files /dev/null and b/src/main/resources/static/image/flag/ba.png differ diff --git a/src/main/resources/static/image/flag/bb.png b/src/main/resources/static/image/flag/bb.png new file mode 100644 index 0000000..0df19c7 Binary files /dev/null and b/src/main/resources/static/image/flag/bb.png differ diff --git a/src/main/resources/static/image/flag/bd.png b/src/main/resources/static/image/flag/bd.png new file mode 100644 index 0000000..076a8bf Binary files /dev/null and b/src/main/resources/static/image/flag/bd.png differ diff --git a/src/main/resources/static/image/flag/be.png b/src/main/resources/static/image/flag/be.png new file mode 100644 index 0000000..d86ebc8 Binary files /dev/null and b/src/main/resources/static/image/flag/be.png differ diff --git a/src/main/resources/static/image/flag/bf.png b/src/main/resources/static/image/flag/bf.png new file mode 100644 index 0000000..ab5ce8f Binary files /dev/null and b/src/main/resources/static/image/flag/bf.png differ diff --git a/src/main/resources/static/image/flag/bg.png b/src/main/resources/static/image/flag/bg.png new file mode 100644 index 0000000..0469f06 Binary files /dev/null and b/src/main/resources/static/image/flag/bg.png differ diff --git a/src/main/resources/static/image/flag/bh.png b/src/main/resources/static/image/flag/bh.png new file mode 100644 index 0000000..ea8ce68 Binary files /dev/null and b/src/main/resources/static/image/flag/bh.png differ diff --git a/src/main/resources/static/image/flag/bi.png b/src/main/resources/static/image/flag/bi.png new file mode 100644 index 0000000..5cc2e30 Binary files /dev/null and b/src/main/resources/static/image/flag/bi.png differ diff --git a/src/main/resources/static/image/flag/bj.png b/src/main/resources/static/image/flag/bj.png new file mode 100644 index 0000000..1cc8b45 Binary files /dev/null and b/src/main/resources/static/image/flag/bj.png differ diff --git a/src/main/resources/static/image/flag/bm.png b/src/main/resources/static/image/flag/bm.png new file mode 100644 index 0000000..c0c7aea Binary files /dev/null and b/src/main/resources/static/image/flag/bm.png differ diff --git a/src/main/resources/static/image/flag/bn.png b/src/main/resources/static/image/flag/bn.png new file mode 100644 index 0000000..8fb0984 Binary files /dev/null and b/src/main/resources/static/image/flag/bn.png differ diff --git a/src/main/resources/static/image/flag/bo.png b/src/main/resources/static/image/flag/bo.png new file mode 100644 index 0000000..ce7ba52 Binary files /dev/null and b/src/main/resources/static/image/flag/bo.png differ diff --git a/src/main/resources/static/image/flag/br.png b/src/main/resources/static/image/flag/br.png new file mode 100644 index 0000000..9b1a553 Binary files /dev/null and b/src/main/resources/static/image/flag/br.png differ diff --git a/src/main/resources/static/image/flag/bs.png b/src/main/resources/static/image/flag/bs.png new file mode 100644 index 0000000..639fa6c Binary files /dev/null and b/src/main/resources/static/image/flag/bs.png differ diff --git a/src/main/resources/static/image/flag/bt.png b/src/main/resources/static/image/flag/bt.png new file mode 100644 index 0000000..1d512df Binary files /dev/null and b/src/main/resources/static/image/flag/bt.png differ diff --git a/src/main/resources/static/image/flag/bv.png b/src/main/resources/static/image/flag/bv.png new file mode 100644 index 0000000..160b6b5 Binary files /dev/null and b/src/main/resources/static/image/flag/bv.png differ diff --git a/src/main/resources/static/image/flag/bw.png b/src/main/resources/static/image/flag/bw.png new file mode 100644 index 0000000..fcb1039 Binary files /dev/null and b/src/main/resources/static/image/flag/bw.png differ diff --git a/src/main/resources/static/image/flag/by.png b/src/main/resources/static/image/flag/by.png new file mode 100644 index 0000000..504774e Binary files /dev/null and b/src/main/resources/static/image/flag/by.png differ diff --git a/src/main/resources/static/image/flag/bz.png b/src/main/resources/static/image/flag/bz.png new file mode 100644 index 0000000..be63ee1 Binary files /dev/null and b/src/main/resources/static/image/flag/bz.png differ diff --git a/src/main/resources/static/image/flag/ca.png b/src/main/resources/static/image/flag/ca.png new file mode 100644 index 0000000..1f20419 Binary files /dev/null and b/src/main/resources/static/image/flag/ca.png differ diff --git a/src/main/resources/static/image/flag/cc.png b/src/main/resources/static/image/flag/cc.png new file mode 100644 index 0000000..aed3d3b Binary files /dev/null and b/src/main/resources/static/image/flag/cc.png differ diff --git a/src/main/resources/static/image/flag/cd.png b/src/main/resources/static/image/flag/cd.png new file mode 100644 index 0000000..a072ac2 Binary files /dev/null and b/src/main/resources/static/image/flag/cd.png differ diff --git a/src/main/resources/static/image/flag/cf.png b/src/main/resources/static/image/flag/cf.png new file mode 100644 index 0000000..da687bd Binary files /dev/null and b/src/main/resources/static/image/flag/cf.png differ diff --git a/src/main/resources/static/image/flag/cg.png b/src/main/resources/static/image/flag/cg.png new file mode 100644 index 0000000..a859792 Binary files /dev/null and b/src/main/resources/static/image/flag/cg.png differ diff --git a/src/main/resources/static/image/flag/ch.png b/src/main/resources/static/image/flag/ch.png new file mode 100644 index 0000000..242ec01 Binary files /dev/null and b/src/main/resources/static/image/flag/ch.png differ diff --git a/src/main/resources/static/image/flag/ci.png b/src/main/resources/static/image/flag/ci.png new file mode 100644 index 0000000..3f2c62e Binary files /dev/null and b/src/main/resources/static/image/flag/ci.png differ diff --git a/src/main/resources/static/image/flag/ck.png b/src/main/resources/static/image/flag/ck.png new file mode 100644 index 0000000..746d3d6 Binary files /dev/null and b/src/main/resources/static/image/flag/ck.png differ diff --git a/src/main/resources/static/image/flag/cl.png b/src/main/resources/static/image/flag/cl.png new file mode 100644 index 0000000..29c6d61 Binary files /dev/null and b/src/main/resources/static/image/flag/cl.png differ diff --git a/src/main/resources/static/image/flag/cm.png b/src/main/resources/static/image/flag/cm.png new file mode 100644 index 0000000..f65c5bd Binary files /dev/null and b/src/main/resources/static/image/flag/cm.png differ diff --git a/src/main/resources/static/image/flag/cn.png b/src/main/resources/static/image/flag/cn.png new file mode 100644 index 0000000..8914414 Binary files /dev/null and b/src/main/resources/static/image/flag/cn.png differ diff --git a/src/main/resources/static/image/flag/co.png b/src/main/resources/static/image/flag/co.png new file mode 100644 index 0000000..a118ff4 Binary files /dev/null and b/src/main/resources/static/image/flag/co.png differ diff --git a/src/main/resources/static/image/flag/cr.png b/src/main/resources/static/image/flag/cr.png new file mode 100644 index 0000000..c7a3731 Binary files /dev/null and b/src/main/resources/static/image/flag/cr.png differ diff --git a/src/main/resources/static/image/flag/cs.png b/src/main/resources/static/image/flag/cs.png new file mode 100644 index 0000000..8254790 Binary files /dev/null and b/src/main/resources/static/image/flag/cs.png differ diff --git a/src/main/resources/static/image/flag/cu.png b/src/main/resources/static/image/flag/cu.png new file mode 100644 index 0000000..083f1d6 Binary files /dev/null and b/src/main/resources/static/image/flag/cu.png differ diff --git a/src/main/resources/static/image/flag/cv.png b/src/main/resources/static/image/flag/cv.png new file mode 100644 index 0000000..a63f7ea Binary files /dev/null and b/src/main/resources/static/image/flag/cv.png differ diff --git a/src/main/resources/static/image/flag/cx.png b/src/main/resources/static/image/flag/cx.png new file mode 100644 index 0000000..48e31ad Binary files /dev/null and b/src/main/resources/static/image/flag/cx.png differ diff --git a/src/main/resources/static/image/flag/cy.png b/src/main/resources/static/image/flag/cy.png new file mode 100644 index 0000000..5b1ad6c Binary files /dev/null and b/src/main/resources/static/image/flag/cy.png differ diff --git a/src/main/resources/static/image/flag/cz.png b/src/main/resources/static/image/flag/cz.png new file mode 100644 index 0000000..c8403dd Binary files /dev/null and b/src/main/resources/static/image/flag/cz.png differ diff --git a/src/main/resources/static/image/flag/de.png b/src/main/resources/static/image/flag/de.png new file mode 100644 index 0000000..ac4a977 Binary files /dev/null and b/src/main/resources/static/image/flag/de.png differ diff --git a/src/main/resources/static/image/flag/dj.png b/src/main/resources/static/image/flag/dj.png new file mode 100644 index 0000000..582af36 Binary files /dev/null and b/src/main/resources/static/image/flag/dj.png differ diff --git a/src/main/resources/static/image/flag/dk.png b/src/main/resources/static/image/flag/dk.png new file mode 100644 index 0000000..e2993d3 Binary files /dev/null and b/src/main/resources/static/image/flag/dk.png differ diff --git a/src/main/resources/static/image/flag/dm.png b/src/main/resources/static/image/flag/dm.png new file mode 100644 index 0000000..5fbffcb Binary files /dev/null and b/src/main/resources/static/image/flag/dm.png differ diff --git a/src/main/resources/static/image/flag/do.png b/src/main/resources/static/image/flag/do.png new file mode 100644 index 0000000..5a04932 Binary files /dev/null and b/src/main/resources/static/image/flag/do.png differ diff --git a/src/main/resources/static/image/flag/dz.png b/src/main/resources/static/image/flag/dz.png new file mode 100644 index 0000000..335c239 Binary files /dev/null and b/src/main/resources/static/image/flag/dz.png differ diff --git a/src/main/resources/static/image/flag/ec.png b/src/main/resources/static/image/flag/ec.png new file mode 100644 index 0000000..0caa0b1 Binary files /dev/null and b/src/main/resources/static/image/flag/ec.png differ diff --git a/src/main/resources/static/image/flag/ee.png b/src/main/resources/static/image/flag/ee.png new file mode 100644 index 0000000..0c82efb Binary files /dev/null and b/src/main/resources/static/image/flag/ee.png differ diff --git a/src/main/resources/static/image/flag/eg.png b/src/main/resources/static/image/flag/eg.png new file mode 100644 index 0000000..8a3f7a1 Binary files /dev/null and b/src/main/resources/static/image/flag/eg.png differ diff --git a/src/main/resources/static/image/flag/eh.png b/src/main/resources/static/image/flag/eh.png new file mode 100644 index 0000000..90a1195 Binary files /dev/null and b/src/main/resources/static/image/flag/eh.png differ diff --git a/src/main/resources/static/image/flag/england.png b/src/main/resources/static/image/flag/england.png new file mode 100644 index 0000000..3a7311d Binary files /dev/null and b/src/main/resources/static/image/flag/england.png differ diff --git a/src/main/resources/static/image/flag/er.png b/src/main/resources/static/image/flag/er.png new file mode 100644 index 0000000..13065ae Binary files /dev/null and b/src/main/resources/static/image/flag/er.png differ diff --git a/src/main/resources/static/image/flag/es.png b/src/main/resources/static/image/flag/es.png new file mode 100644 index 0000000..c2de2d7 Binary files /dev/null and b/src/main/resources/static/image/flag/es.png differ diff --git a/src/main/resources/static/image/flag/et.png b/src/main/resources/static/image/flag/et.png new file mode 100644 index 0000000..2e893fa Binary files /dev/null and b/src/main/resources/static/image/flag/et.png differ diff --git a/src/main/resources/static/image/flag/fam.png b/src/main/resources/static/image/flag/fam.png new file mode 100644 index 0000000..cf50c75 Binary files /dev/null and b/src/main/resources/static/image/flag/fam.png differ diff --git a/src/main/resources/static/image/flag/fi.png b/src/main/resources/static/image/flag/fi.png new file mode 100644 index 0000000..14ec091 Binary files /dev/null and b/src/main/resources/static/image/flag/fi.png differ diff --git a/src/main/resources/static/image/flag/fj.png b/src/main/resources/static/image/flag/fj.png new file mode 100644 index 0000000..cee9988 Binary files /dev/null and b/src/main/resources/static/image/flag/fj.png differ diff --git a/src/main/resources/static/image/flag/fk.png b/src/main/resources/static/image/flag/fk.png new file mode 100644 index 0000000..ceaeb27 Binary files /dev/null and b/src/main/resources/static/image/flag/fk.png differ diff --git a/src/main/resources/static/image/flag/fm.png b/src/main/resources/static/image/flag/fm.png new file mode 100644 index 0000000..066bb24 Binary files /dev/null and b/src/main/resources/static/image/flag/fm.png differ diff --git a/src/main/resources/static/image/flag/fo.png b/src/main/resources/static/image/flag/fo.png new file mode 100644 index 0000000..cbceb80 Binary files /dev/null and b/src/main/resources/static/image/flag/fo.png differ diff --git a/src/main/resources/static/image/flag/fr.png b/src/main/resources/static/image/flag/fr.png new file mode 100644 index 0000000..8332c4e Binary files /dev/null and b/src/main/resources/static/image/flag/fr.png differ diff --git a/src/main/resources/static/image/flag/ga.png b/src/main/resources/static/image/flag/ga.png new file mode 100644 index 0000000..0e0d434 Binary files /dev/null and b/src/main/resources/static/image/flag/ga.png differ diff --git a/src/main/resources/static/image/flag/gb.png b/src/main/resources/static/image/flag/gb.png new file mode 100644 index 0000000..5c4d301 Binary files /dev/null and b/src/main/resources/static/image/flag/gb.png differ diff --git a/src/main/resources/static/image/flag/gd.png b/src/main/resources/static/image/flag/gd.png new file mode 100644 index 0000000..9ab57f5 Binary files /dev/null and b/src/main/resources/static/image/flag/gd.png differ diff --git a/src/main/resources/static/image/flag/ge.png b/src/main/resources/static/image/flag/ge.png new file mode 100644 index 0000000..728d970 Binary files /dev/null and b/src/main/resources/static/image/flag/ge.png differ diff --git a/src/main/resources/static/image/flag/gh.png b/src/main/resources/static/image/flag/gh.png new file mode 100644 index 0000000..4e2f896 Binary files /dev/null and b/src/main/resources/static/image/flag/gh.png differ diff --git a/src/main/resources/static/image/flag/gi.png b/src/main/resources/static/image/flag/gi.png new file mode 100644 index 0000000..e76797f Binary files /dev/null and b/src/main/resources/static/image/flag/gi.png differ diff --git a/src/main/resources/static/image/flag/gl.png b/src/main/resources/static/image/flag/gl.png new file mode 100644 index 0000000..ef12a73 Binary files /dev/null and b/src/main/resources/static/image/flag/gl.png differ diff --git a/src/main/resources/static/image/flag/gm.png b/src/main/resources/static/image/flag/gm.png new file mode 100644 index 0000000..0720b66 Binary files /dev/null and b/src/main/resources/static/image/flag/gm.png differ diff --git a/src/main/resources/static/image/flag/gn.png b/src/main/resources/static/image/flag/gn.png new file mode 100644 index 0000000..ea660b0 Binary files /dev/null and b/src/main/resources/static/image/flag/gn.png differ diff --git a/src/main/resources/static/image/flag/gp.png b/src/main/resources/static/image/flag/gp.png new file mode 100644 index 0000000..dbb086d Binary files /dev/null and b/src/main/resources/static/image/flag/gp.png differ diff --git a/src/main/resources/static/image/flag/gq.png b/src/main/resources/static/image/flag/gq.png new file mode 100644 index 0000000..ebe20a2 Binary files /dev/null and b/src/main/resources/static/image/flag/gq.png differ diff --git a/src/main/resources/static/image/flag/gr.png b/src/main/resources/static/image/flag/gr.png new file mode 100644 index 0000000..8651ade Binary files /dev/null and b/src/main/resources/static/image/flag/gr.png differ diff --git a/src/main/resources/static/image/flag/gs.png b/src/main/resources/static/image/flag/gs.png new file mode 100644 index 0000000..7ef0bf5 Binary files /dev/null and b/src/main/resources/static/image/flag/gs.png differ diff --git a/src/main/resources/static/image/flag/gt.png b/src/main/resources/static/image/flag/gt.png new file mode 100644 index 0000000..c43a70d Binary files /dev/null and b/src/main/resources/static/image/flag/gt.png differ diff --git a/src/main/resources/static/image/flag/gu.png b/src/main/resources/static/image/flag/gu.png new file mode 100644 index 0000000..92f37c0 Binary files /dev/null and b/src/main/resources/static/image/flag/gu.png differ diff --git a/src/main/resources/static/image/flag/gw.png b/src/main/resources/static/image/flag/gw.png new file mode 100644 index 0000000..b37bcf0 Binary files /dev/null and b/src/main/resources/static/image/flag/gw.png differ diff --git a/src/main/resources/static/image/flag/gy.png b/src/main/resources/static/image/flag/gy.png new file mode 100644 index 0000000..22cbe2f Binary files /dev/null and b/src/main/resources/static/image/flag/gy.png differ diff --git a/src/main/resources/static/image/flag/hk.png b/src/main/resources/static/image/flag/hk.png new file mode 100644 index 0000000..d5c380c Binary files /dev/null and b/src/main/resources/static/image/flag/hk.png differ diff --git a/src/main/resources/static/image/flag/hn.png b/src/main/resources/static/image/flag/hn.png new file mode 100644 index 0000000..96f8388 Binary files /dev/null and b/src/main/resources/static/image/flag/hn.png differ diff --git a/src/main/resources/static/image/flag/hr.png b/src/main/resources/static/image/flag/hr.png new file mode 100644 index 0000000..696b515 Binary files /dev/null and b/src/main/resources/static/image/flag/hr.png differ diff --git a/src/main/resources/static/image/flag/ht.png b/src/main/resources/static/image/flag/ht.png new file mode 100644 index 0000000..416052a Binary files /dev/null and b/src/main/resources/static/image/flag/ht.png differ diff --git a/src/main/resources/static/image/flag/hu.png b/src/main/resources/static/image/flag/hu.png new file mode 100644 index 0000000..7baafe4 Binary files /dev/null and b/src/main/resources/static/image/flag/hu.png differ diff --git a/src/main/resources/static/image/flag/id.png b/src/main/resources/static/image/flag/id.png new file mode 100644 index 0000000..c6bc0fa Binary files /dev/null and b/src/main/resources/static/image/flag/id.png differ diff --git a/src/main/resources/static/image/flag/ie.png b/src/main/resources/static/image/flag/ie.png new file mode 100644 index 0000000..26baa31 Binary files /dev/null and b/src/main/resources/static/image/flag/ie.png differ diff --git a/src/main/resources/static/image/flag/il.png b/src/main/resources/static/image/flag/il.png new file mode 100644 index 0000000..2ca772d Binary files /dev/null and b/src/main/resources/static/image/flag/il.png differ diff --git a/src/main/resources/static/image/flag/in.png b/src/main/resources/static/image/flag/in.png new file mode 100644 index 0000000..e4d7e81 Binary files /dev/null and b/src/main/resources/static/image/flag/in.png differ diff --git a/src/main/resources/static/image/flag/io.png b/src/main/resources/static/image/flag/io.png new file mode 100644 index 0000000..3e74b6a Binary files /dev/null and b/src/main/resources/static/image/flag/io.png differ diff --git a/src/main/resources/static/image/flag/iq.png b/src/main/resources/static/image/flag/iq.png new file mode 100644 index 0000000..878a351 Binary files /dev/null and b/src/main/resources/static/image/flag/iq.png differ diff --git a/src/main/resources/static/image/flag/ir.png b/src/main/resources/static/image/flag/ir.png new file mode 100644 index 0000000..c5fd136 Binary files /dev/null and b/src/main/resources/static/image/flag/ir.png differ diff --git a/src/main/resources/static/image/flag/is.png b/src/main/resources/static/image/flag/is.png new file mode 100644 index 0000000..b8f6d0f Binary files /dev/null and b/src/main/resources/static/image/flag/is.png differ diff --git a/src/main/resources/static/image/flag/it.png b/src/main/resources/static/image/flag/it.png new file mode 100644 index 0000000..89692f7 Binary files /dev/null and b/src/main/resources/static/image/flag/it.png differ diff --git a/src/main/resources/static/image/flag/jm.png b/src/main/resources/static/image/flag/jm.png new file mode 100644 index 0000000..7be119e Binary files /dev/null and b/src/main/resources/static/image/flag/jm.png differ diff --git a/src/main/resources/static/image/flag/jo.png b/src/main/resources/static/image/flag/jo.png new file mode 100644 index 0000000..11bd497 Binary files /dev/null and b/src/main/resources/static/image/flag/jo.png differ diff --git a/src/main/resources/static/image/flag/jp.png b/src/main/resources/static/image/flag/jp.png new file mode 100644 index 0000000..325fbad Binary files /dev/null and b/src/main/resources/static/image/flag/jp.png differ diff --git a/src/main/resources/static/image/flag/ke.png b/src/main/resources/static/image/flag/ke.png new file mode 100644 index 0000000..51879ad Binary files /dev/null and b/src/main/resources/static/image/flag/ke.png differ diff --git a/src/main/resources/static/image/flag/kg.png b/src/main/resources/static/image/flag/kg.png new file mode 100644 index 0000000..0a818f6 Binary files /dev/null and b/src/main/resources/static/image/flag/kg.png differ diff --git a/src/main/resources/static/image/flag/kh.png b/src/main/resources/static/image/flag/kh.png new file mode 100644 index 0000000..30f6bb1 Binary files /dev/null and b/src/main/resources/static/image/flag/kh.png differ diff --git a/src/main/resources/static/image/flag/ki.png b/src/main/resources/static/image/flag/ki.png new file mode 100644 index 0000000..2dcce4b Binary files /dev/null and b/src/main/resources/static/image/flag/ki.png differ diff --git a/src/main/resources/static/image/flag/km.png b/src/main/resources/static/image/flag/km.png new file mode 100644 index 0000000..812b2f5 Binary files /dev/null and b/src/main/resources/static/image/flag/km.png differ diff --git a/src/main/resources/static/image/flag/kn.png b/src/main/resources/static/image/flag/kn.png new file mode 100644 index 0000000..febd5b4 Binary files /dev/null and b/src/main/resources/static/image/flag/kn.png differ diff --git a/src/main/resources/static/image/flag/kp.png b/src/main/resources/static/image/flag/kp.png new file mode 100644 index 0000000..d3d509a Binary files /dev/null and b/src/main/resources/static/image/flag/kp.png differ diff --git a/src/main/resources/static/image/flag/kr.png b/src/main/resources/static/image/flag/kr.png new file mode 100644 index 0000000..9c0a78e Binary files /dev/null and b/src/main/resources/static/image/flag/kr.png differ diff --git a/src/main/resources/static/image/flag/kw.png b/src/main/resources/static/image/flag/kw.png new file mode 100644 index 0000000..96546da Binary files /dev/null and b/src/main/resources/static/image/flag/kw.png differ diff --git a/src/main/resources/static/image/flag/ky.png b/src/main/resources/static/image/flag/ky.png new file mode 100644 index 0000000..15c5f8e Binary files /dev/null and b/src/main/resources/static/image/flag/ky.png differ diff --git a/src/main/resources/static/image/flag/kz.png b/src/main/resources/static/image/flag/kz.png new file mode 100644 index 0000000..45a8c88 Binary files /dev/null and b/src/main/resources/static/image/flag/kz.png differ diff --git a/src/main/resources/static/image/flag/la.png b/src/main/resources/static/image/flag/la.png new file mode 100644 index 0000000..e28acd0 Binary files /dev/null and b/src/main/resources/static/image/flag/la.png differ diff --git a/src/main/resources/static/image/flag/lb.png b/src/main/resources/static/image/flag/lb.png new file mode 100644 index 0000000..d0d452b Binary files /dev/null and b/src/main/resources/static/image/flag/lb.png differ diff --git a/src/main/resources/static/image/flag/lc.png b/src/main/resources/static/image/flag/lc.png new file mode 100644 index 0000000..8fc12b4 Binary files /dev/null and b/src/main/resources/static/image/flag/lc.png differ diff --git a/src/main/resources/static/image/flag/li.png b/src/main/resources/static/image/flag/li.png new file mode 100644 index 0000000..6469909 Binary files /dev/null and b/src/main/resources/static/image/flag/li.png differ diff --git a/src/main/resources/static/image/flag/lk.png b/src/main/resources/static/image/flag/lk.png new file mode 100644 index 0000000..088aad6 Binary files /dev/null and b/src/main/resources/static/image/flag/lk.png differ diff --git a/src/main/resources/static/image/flag/lr.png b/src/main/resources/static/image/flag/lr.png new file mode 100644 index 0000000..89a5bc7 Binary files /dev/null and b/src/main/resources/static/image/flag/lr.png differ diff --git a/src/main/resources/static/image/flag/ls.png b/src/main/resources/static/image/flag/ls.png new file mode 100644 index 0000000..33fdef1 Binary files /dev/null and b/src/main/resources/static/image/flag/ls.png differ diff --git a/src/main/resources/static/image/flag/lt.png b/src/main/resources/static/image/flag/lt.png new file mode 100644 index 0000000..c8ef0da Binary files /dev/null and b/src/main/resources/static/image/flag/lt.png differ diff --git a/src/main/resources/static/image/flag/lu.png b/src/main/resources/static/image/flag/lu.png new file mode 100644 index 0000000..4cabba9 Binary files /dev/null and b/src/main/resources/static/image/flag/lu.png differ diff --git a/src/main/resources/static/image/flag/lv.png b/src/main/resources/static/image/flag/lv.png new file mode 100644 index 0000000..49b6998 Binary files /dev/null and b/src/main/resources/static/image/flag/lv.png differ diff --git a/src/main/resources/static/image/flag/ly.png b/src/main/resources/static/image/flag/ly.png new file mode 100644 index 0000000..b163a9f Binary files /dev/null and b/src/main/resources/static/image/flag/ly.png differ diff --git a/src/main/resources/static/image/flag/ma.png b/src/main/resources/static/image/flag/ma.png new file mode 100644 index 0000000..f386770 Binary files /dev/null and b/src/main/resources/static/image/flag/ma.png differ diff --git a/src/main/resources/static/image/flag/mc.png b/src/main/resources/static/image/flag/mc.png new file mode 100644 index 0000000..1aa830f Binary files /dev/null and b/src/main/resources/static/image/flag/mc.png differ diff --git a/src/main/resources/static/image/flag/md.png b/src/main/resources/static/image/flag/md.png new file mode 100644 index 0000000..4e92c18 Binary files /dev/null and b/src/main/resources/static/image/flag/md.png differ diff --git a/src/main/resources/static/image/flag/mg.png b/src/main/resources/static/image/flag/mg.png new file mode 100644 index 0000000..d2715b3 Binary files /dev/null and b/src/main/resources/static/image/flag/mg.png differ diff --git a/src/main/resources/static/image/flag/mh.png b/src/main/resources/static/image/flag/mh.png new file mode 100644 index 0000000..fb523a8 Binary files /dev/null and b/src/main/resources/static/image/flag/mh.png differ diff --git a/src/main/resources/static/image/flag/mk.png b/src/main/resources/static/image/flag/mk.png new file mode 100644 index 0000000..db173aa Binary files /dev/null and b/src/main/resources/static/image/flag/mk.png differ diff --git a/src/main/resources/static/image/flag/ml.png b/src/main/resources/static/image/flag/ml.png new file mode 100644 index 0000000..2cec8ba Binary files /dev/null and b/src/main/resources/static/image/flag/ml.png differ diff --git a/src/main/resources/static/image/flag/mm.png b/src/main/resources/static/image/flag/mm.png new file mode 100644 index 0000000..f464f67 Binary files /dev/null and b/src/main/resources/static/image/flag/mm.png differ diff --git a/src/main/resources/static/image/flag/mn.png b/src/main/resources/static/image/flag/mn.png new file mode 100644 index 0000000..9396355 Binary files /dev/null and b/src/main/resources/static/image/flag/mn.png differ diff --git a/src/main/resources/static/image/flag/mo.png b/src/main/resources/static/image/flag/mo.png new file mode 100644 index 0000000..deb801d Binary files /dev/null and b/src/main/resources/static/image/flag/mo.png differ diff --git a/src/main/resources/static/image/flag/mp.png b/src/main/resources/static/image/flag/mp.png new file mode 100644 index 0000000..298d588 Binary files /dev/null and b/src/main/resources/static/image/flag/mp.png differ diff --git a/src/main/resources/static/image/flag/mq.png b/src/main/resources/static/image/flag/mq.png new file mode 100644 index 0000000..010143b Binary files /dev/null and b/src/main/resources/static/image/flag/mq.png differ diff --git a/src/main/resources/static/image/flag/mr.png b/src/main/resources/static/image/flag/mr.png new file mode 100644 index 0000000..319546b Binary files /dev/null and b/src/main/resources/static/image/flag/mr.png differ diff --git a/src/main/resources/static/image/flag/ms.png b/src/main/resources/static/image/flag/ms.png new file mode 100644 index 0000000..d4cbb43 Binary files /dev/null and b/src/main/resources/static/image/flag/ms.png differ diff --git a/src/main/resources/static/image/flag/mt.png b/src/main/resources/static/image/flag/mt.png new file mode 100644 index 0000000..00af948 Binary files /dev/null and b/src/main/resources/static/image/flag/mt.png differ diff --git a/src/main/resources/static/image/flag/mu.png b/src/main/resources/static/image/flag/mu.png new file mode 100644 index 0000000..b7fdce1 Binary files /dev/null and b/src/main/resources/static/image/flag/mu.png differ diff --git a/src/main/resources/static/image/flag/mv.png b/src/main/resources/static/image/flag/mv.png new file mode 100644 index 0000000..5073d9e Binary files /dev/null and b/src/main/resources/static/image/flag/mv.png differ diff --git a/src/main/resources/static/image/flag/mw.png b/src/main/resources/static/image/flag/mw.png new file mode 100644 index 0000000..13886e9 Binary files /dev/null and b/src/main/resources/static/image/flag/mw.png differ diff --git a/src/main/resources/static/image/flag/mx.png b/src/main/resources/static/image/flag/mx.png new file mode 100644 index 0000000..5bc58ab Binary files /dev/null and b/src/main/resources/static/image/flag/mx.png differ diff --git a/src/main/resources/static/image/flag/my.png b/src/main/resources/static/image/flag/my.png new file mode 100644 index 0000000..9034cba Binary files /dev/null and b/src/main/resources/static/image/flag/my.png differ diff --git a/src/main/resources/static/image/flag/mz.png b/src/main/resources/static/image/flag/mz.png new file mode 100644 index 0000000..76405e0 Binary files /dev/null and b/src/main/resources/static/image/flag/mz.png differ diff --git a/src/main/resources/static/image/flag/na.png b/src/main/resources/static/image/flag/na.png new file mode 100644 index 0000000..63358c6 Binary files /dev/null and b/src/main/resources/static/image/flag/na.png differ diff --git a/src/main/resources/static/image/flag/nc.png b/src/main/resources/static/image/flag/nc.png new file mode 100644 index 0000000..2cad283 Binary files /dev/null and b/src/main/resources/static/image/flag/nc.png differ diff --git a/src/main/resources/static/image/flag/ne.png b/src/main/resources/static/image/flag/ne.png new file mode 100644 index 0000000..d85f424 Binary files /dev/null and b/src/main/resources/static/image/flag/ne.png differ diff --git a/src/main/resources/static/image/flag/nf.png b/src/main/resources/static/image/flag/nf.png new file mode 100644 index 0000000..f9bcdda Binary files /dev/null and b/src/main/resources/static/image/flag/nf.png differ diff --git a/src/main/resources/static/image/flag/ng.png b/src/main/resources/static/image/flag/ng.png new file mode 100644 index 0000000..3eea2e0 Binary files /dev/null and b/src/main/resources/static/image/flag/ng.png differ diff --git a/src/main/resources/static/image/flag/ni.png b/src/main/resources/static/image/flag/ni.png new file mode 100644 index 0000000..3969aaa Binary files /dev/null and b/src/main/resources/static/image/flag/ni.png differ diff --git a/src/main/resources/static/image/flag/nl.png b/src/main/resources/static/image/flag/nl.png new file mode 100644 index 0000000..fe44791 Binary files /dev/null and b/src/main/resources/static/image/flag/nl.png differ diff --git a/src/main/resources/static/image/flag/no.png b/src/main/resources/static/image/flag/no.png new file mode 100644 index 0000000..160b6b5 Binary files /dev/null and b/src/main/resources/static/image/flag/no.png differ diff --git a/src/main/resources/static/image/flag/np.png b/src/main/resources/static/image/flag/np.png new file mode 100644 index 0000000..aeb058b Binary files /dev/null and b/src/main/resources/static/image/flag/np.png differ diff --git a/src/main/resources/static/image/flag/nr.png b/src/main/resources/static/image/flag/nr.png new file mode 100644 index 0000000..705fc33 Binary files /dev/null and b/src/main/resources/static/image/flag/nr.png differ diff --git a/src/main/resources/static/image/flag/nu.png b/src/main/resources/static/image/flag/nu.png new file mode 100644 index 0000000..c3ce4ae Binary files /dev/null and b/src/main/resources/static/image/flag/nu.png differ diff --git a/src/main/resources/static/image/flag/nz.png b/src/main/resources/static/image/flag/nz.png new file mode 100644 index 0000000..10d6306 Binary files /dev/null and b/src/main/resources/static/image/flag/nz.png differ diff --git a/src/main/resources/static/image/flag/om.png b/src/main/resources/static/image/flag/om.png new file mode 100644 index 0000000..2ffba7e Binary files /dev/null and b/src/main/resources/static/image/flag/om.png differ diff --git a/src/main/resources/static/image/flag/pa.png b/src/main/resources/static/image/flag/pa.png new file mode 100644 index 0000000..9b2ee9a Binary files /dev/null and b/src/main/resources/static/image/flag/pa.png differ diff --git a/src/main/resources/static/image/flag/pe.png b/src/main/resources/static/image/flag/pe.png new file mode 100644 index 0000000..62a0497 Binary files /dev/null and b/src/main/resources/static/image/flag/pe.png differ diff --git a/src/main/resources/static/image/flag/pf.png b/src/main/resources/static/image/flag/pf.png new file mode 100644 index 0000000..771a0f6 Binary files /dev/null and b/src/main/resources/static/image/flag/pf.png differ diff --git a/src/main/resources/static/image/flag/pg.png b/src/main/resources/static/image/flag/pg.png new file mode 100644 index 0000000..10d6233 Binary files /dev/null and b/src/main/resources/static/image/flag/pg.png differ diff --git a/src/main/resources/static/image/flag/ph.png b/src/main/resources/static/image/flag/ph.png new file mode 100644 index 0000000..b89e159 Binary files /dev/null and b/src/main/resources/static/image/flag/ph.png differ diff --git a/src/main/resources/static/image/flag/pk.png b/src/main/resources/static/image/flag/pk.png new file mode 100644 index 0000000..e9df70c Binary files /dev/null and b/src/main/resources/static/image/flag/pk.png differ diff --git a/src/main/resources/static/image/flag/pl.png b/src/main/resources/static/image/flag/pl.png new file mode 100644 index 0000000..d413d01 Binary files /dev/null and b/src/main/resources/static/image/flag/pl.png differ diff --git a/src/main/resources/static/image/flag/pm.png b/src/main/resources/static/image/flag/pm.png new file mode 100644 index 0000000..ba91d2c Binary files /dev/null and b/src/main/resources/static/image/flag/pm.png differ diff --git a/src/main/resources/static/image/flag/pn.png b/src/main/resources/static/image/flag/pn.png new file mode 100644 index 0000000..aa9344f Binary files /dev/null and b/src/main/resources/static/image/flag/pn.png differ diff --git a/src/main/resources/static/image/flag/pr.png b/src/main/resources/static/image/flag/pr.png new file mode 100644 index 0000000..82d9130 Binary files /dev/null and b/src/main/resources/static/image/flag/pr.png differ diff --git a/src/main/resources/static/image/flag/ps.png b/src/main/resources/static/image/flag/ps.png new file mode 100644 index 0000000..f5f5477 Binary files /dev/null and b/src/main/resources/static/image/flag/ps.png differ diff --git a/src/main/resources/static/image/flag/pt.png b/src/main/resources/static/image/flag/pt.png new file mode 100644 index 0000000..ece7980 Binary files /dev/null and b/src/main/resources/static/image/flag/pt.png differ diff --git a/src/main/resources/static/image/flag/pw.png b/src/main/resources/static/image/flag/pw.png new file mode 100644 index 0000000..6178b25 Binary files /dev/null and b/src/main/resources/static/image/flag/pw.png differ diff --git a/src/main/resources/static/image/flag/py.png b/src/main/resources/static/image/flag/py.png new file mode 100644 index 0000000..cb8723c Binary files /dev/null and b/src/main/resources/static/image/flag/py.png differ diff --git a/src/main/resources/static/image/flag/qa.png b/src/main/resources/static/image/flag/qa.png new file mode 100644 index 0000000..ed4c621 Binary files /dev/null and b/src/main/resources/static/image/flag/qa.png differ diff --git a/src/main/resources/static/image/flag/ro.png b/src/main/resources/static/image/flag/ro.png new file mode 100644 index 0000000..57e74a6 Binary files /dev/null and b/src/main/resources/static/image/flag/ro.png differ diff --git a/src/main/resources/static/image/flag/ru.png b/src/main/resources/static/image/flag/ru.png new file mode 100644 index 0000000..47da421 Binary files /dev/null and b/src/main/resources/static/image/flag/ru.png differ diff --git a/src/main/resources/static/image/flag/rw.png b/src/main/resources/static/image/flag/rw.png new file mode 100644 index 0000000..5356491 Binary files /dev/null and b/src/main/resources/static/image/flag/rw.png differ diff --git a/src/main/resources/static/image/flag/sa.png b/src/main/resources/static/image/flag/sa.png new file mode 100644 index 0000000..b4641c7 Binary files /dev/null and b/src/main/resources/static/image/flag/sa.png differ diff --git a/src/main/resources/static/image/flag/sb.png b/src/main/resources/static/image/flag/sb.png new file mode 100644 index 0000000..a9937cc Binary files /dev/null and b/src/main/resources/static/image/flag/sb.png differ diff --git a/src/main/resources/static/image/flag/sc.png b/src/main/resources/static/image/flag/sc.png new file mode 100644 index 0000000..39ee371 Binary files /dev/null and b/src/main/resources/static/image/flag/sc.png differ diff --git a/src/main/resources/static/image/flag/scotland.png b/src/main/resources/static/image/flag/scotland.png new file mode 100644 index 0000000..a0e57b4 Binary files /dev/null and b/src/main/resources/static/image/flag/scotland.png differ diff --git a/src/main/resources/static/image/flag/sd.png b/src/main/resources/static/image/flag/sd.png new file mode 100644 index 0000000..eaab69e Binary files /dev/null and b/src/main/resources/static/image/flag/sd.png differ diff --git a/src/main/resources/static/image/flag/se.png b/src/main/resources/static/image/flag/se.png new file mode 100644 index 0000000..1994653 Binary files /dev/null and b/src/main/resources/static/image/flag/se.png differ diff --git a/src/main/resources/static/image/flag/sg.png b/src/main/resources/static/image/flag/sg.png new file mode 100644 index 0000000..dd34d61 Binary files /dev/null and b/src/main/resources/static/image/flag/sg.png differ diff --git a/src/main/resources/static/image/flag/sh.png b/src/main/resources/static/image/flag/sh.png new file mode 100644 index 0000000..4b1d2a2 Binary files /dev/null and b/src/main/resources/static/image/flag/sh.png differ diff --git a/src/main/resources/static/image/flag/si.png b/src/main/resources/static/image/flag/si.png new file mode 100644 index 0000000..bb1476f Binary files /dev/null and b/src/main/resources/static/image/flag/si.png differ diff --git a/src/main/resources/static/image/flag/sk.png b/src/main/resources/static/image/flag/sk.png new file mode 100644 index 0000000..7ccbc82 Binary files /dev/null and b/src/main/resources/static/image/flag/sk.png differ diff --git a/src/main/resources/static/image/flag/sl.png b/src/main/resources/static/image/flag/sl.png new file mode 100644 index 0000000..12d812d Binary files /dev/null and b/src/main/resources/static/image/flag/sl.png differ diff --git a/src/main/resources/static/image/flag/sm.png b/src/main/resources/static/image/flag/sm.png new file mode 100644 index 0000000..3df2fdc Binary files /dev/null and b/src/main/resources/static/image/flag/sm.png differ diff --git a/src/main/resources/static/image/flag/sn.png b/src/main/resources/static/image/flag/sn.png new file mode 100644 index 0000000..eabb71d Binary files /dev/null and b/src/main/resources/static/image/flag/sn.png differ diff --git a/src/main/resources/static/image/flag/so.png b/src/main/resources/static/image/flag/so.png new file mode 100644 index 0000000..4a1ea4b Binary files /dev/null and b/src/main/resources/static/image/flag/so.png differ diff --git a/src/main/resources/static/image/flag/sr.png b/src/main/resources/static/image/flag/sr.png new file mode 100644 index 0000000..5eff927 Binary files /dev/null and b/src/main/resources/static/image/flag/sr.png differ diff --git a/src/main/resources/static/image/flag/st.png b/src/main/resources/static/image/flag/st.png new file mode 100644 index 0000000..2978557 Binary files /dev/null and b/src/main/resources/static/image/flag/st.png differ diff --git a/src/main/resources/static/image/flag/sv.png b/src/main/resources/static/image/flag/sv.png new file mode 100644 index 0000000..2498799 Binary files /dev/null and b/src/main/resources/static/image/flag/sv.png differ diff --git a/src/main/resources/static/image/flag/sy.png b/src/main/resources/static/image/flag/sy.png new file mode 100644 index 0000000..f5ce30d Binary files /dev/null and b/src/main/resources/static/image/flag/sy.png differ diff --git a/src/main/resources/static/image/flag/sz.png b/src/main/resources/static/image/flag/sz.png new file mode 100644 index 0000000..914ee86 Binary files /dev/null and b/src/main/resources/static/image/flag/sz.png differ diff --git a/src/main/resources/static/image/flag/tc.png b/src/main/resources/static/image/flag/tc.png new file mode 100644 index 0000000..8fc1156 Binary files /dev/null and b/src/main/resources/static/image/flag/tc.png differ diff --git a/src/main/resources/static/image/flag/td.png b/src/main/resources/static/image/flag/td.png new file mode 100644 index 0000000..667f21f Binary files /dev/null and b/src/main/resources/static/image/flag/td.png differ diff --git a/src/main/resources/static/image/flag/tf.png b/src/main/resources/static/image/flag/tf.png new file mode 100644 index 0000000..80529a4 Binary files /dev/null and b/src/main/resources/static/image/flag/tf.png differ diff --git a/src/main/resources/static/image/flag/tg.png b/src/main/resources/static/image/flag/tg.png new file mode 100644 index 0000000..3aa00ad Binary files /dev/null and b/src/main/resources/static/image/flag/tg.png differ diff --git a/src/main/resources/static/image/flag/th.png b/src/main/resources/static/image/flag/th.png new file mode 100644 index 0000000..dd8ba91 Binary files /dev/null and b/src/main/resources/static/image/flag/th.png differ diff --git a/src/main/resources/static/image/flag/tj.png b/src/main/resources/static/image/flag/tj.png new file mode 100644 index 0000000..617bf64 Binary files /dev/null and b/src/main/resources/static/image/flag/tj.png differ diff --git a/src/main/resources/static/image/flag/tk.png b/src/main/resources/static/image/flag/tk.png new file mode 100644 index 0000000..67b8c8c Binary files /dev/null and b/src/main/resources/static/image/flag/tk.png differ diff --git a/src/main/resources/static/image/flag/tl.png b/src/main/resources/static/image/flag/tl.png new file mode 100644 index 0000000..77da181 Binary files /dev/null and b/src/main/resources/static/image/flag/tl.png differ diff --git a/src/main/resources/static/image/flag/tm.png b/src/main/resources/static/image/flag/tm.png new file mode 100644 index 0000000..828020e Binary files /dev/null and b/src/main/resources/static/image/flag/tm.png differ diff --git a/src/main/resources/static/image/flag/tn.png b/src/main/resources/static/image/flag/tn.png new file mode 100644 index 0000000..183cdd3 Binary files /dev/null and b/src/main/resources/static/image/flag/tn.png differ diff --git a/src/main/resources/static/image/flag/to.png b/src/main/resources/static/image/flag/to.png new file mode 100644 index 0000000..f89b8ba Binary files /dev/null and b/src/main/resources/static/image/flag/to.png differ diff --git a/src/main/resources/static/image/flag/tr.png b/src/main/resources/static/image/flag/tr.png new file mode 100644 index 0000000..be32f77 Binary files /dev/null and b/src/main/resources/static/image/flag/tr.png differ diff --git a/src/main/resources/static/image/flag/tt.png b/src/main/resources/static/image/flag/tt.png new file mode 100644 index 0000000..2a11c1e Binary files /dev/null and b/src/main/resources/static/image/flag/tt.png differ diff --git a/src/main/resources/static/image/flag/tv.png b/src/main/resources/static/image/flag/tv.png new file mode 100644 index 0000000..28274c5 Binary files /dev/null and b/src/main/resources/static/image/flag/tv.png differ diff --git a/src/main/resources/static/image/flag/tw.png b/src/main/resources/static/image/flag/tw.png new file mode 100644 index 0000000..f31c654 Binary files /dev/null and b/src/main/resources/static/image/flag/tw.png differ diff --git a/src/main/resources/static/image/flag/tz.png b/src/main/resources/static/image/flag/tz.png new file mode 100644 index 0000000..c00ff79 Binary files /dev/null and b/src/main/resources/static/image/flag/tz.png differ diff --git a/src/main/resources/static/image/flag/ua.png b/src/main/resources/static/image/flag/ua.png new file mode 100644 index 0000000..09563a2 Binary files /dev/null and b/src/main/resources/static/image/flag/ua.png differ diff --git a/src/main/resources/static/image/flag/ug.png b/src/main/resources/static/image/flag/ug.png new file mode 100644 index 0000000..33f4aff Binary files /dev/null and b/src/main/resources/static/image/flag/ug.png differ diff --git a/src/main/resources/static/image/flag/um.png b/src/main/resources/static/image/flag/um.png new file mode 100644 index 0000000..c1dd965 Binary files /dev/null and b/src/main/resources/static/image/flag/um.png differ diff --git a/src/main/resources/static/image/flag/us.png b/src/main/resources/static/image/flag/us.png new file mode 100644 index 0000000..10f451f Binary files /dev/null and b/src/main/resources/static/image/flag/us.png differ diff --git a/src/main/resources/static/image/flag/uy.png b/src/main/resources/static/image/flag/uy.png new file mode 100644 index 0000000..31d948a Binary files /dev/null and b/src/main/resources/static/image/flag/uy.png differ diff --git a/src/main/resources/static/image/flag/uz.png b/src/main/resources/static/image/flag/uz.png new file mode 100644 index 0000000..fef5dc1 Binary files /dev/null and b/src/main/resources/static/image/flag/uz.png differ diff --git a/src/main/resources/static/image/flag/va.png b/src/main/resources/static/image/flag/va.png new file mode 100644 index 0000000..b31eaf2 Binary files /dev/null and b/src/main/resources/static/image/flag/va.png differ diff --git a/src/main/resources/static/image/flag/vc.png b/src/main/resources/static/image/flag/vc.png new file mode 100644 index 0000000..8fa17b0 Binary files /dev/null and b/src/main/resources/static/image/flag/vc.png differ diff --git a/src/main/resources/static/image/flag/ve.png b/src/main/resources/static/image/flag/ve.png new file mode 100644 index 0000000..00c90f9 Binary files /dev/null and b/src/main/resources/static/image/flag/ve.png differ diff --git a/src/main/resources/static/image/flag/vg.png b/src/main/resources/static/image/flag/vg.png new file mode 100644 index 0000000..4156907 Binary files /dev/null and b/src/main/resources/static/image/flag/vg.png differ diff --git a/src/main/resources/static/image/flag/vi.png b/src/main/resources/static/image/flag/vi.png new file mode 100644 index 0000000..ed26915 Binary files /dev/null and b/src/main/resources/static/image/flag/vi.png differ diff --git a/src/main/resources/static/image/flag/vn.png b/src/main/resources/static/image/flag/vn.png new file mode 100644 index 0000000..ec7cd48 Binary files /dev/null and b/src/main/resources/static/image/flag/vn.png differ diff --git a/src/main/resources/static/image/flag/vu.png b/src/main/resources/static/image/flag/vu.png new file mode 100644 index 0000000..b3397bc Binary files /dev/null and b/src/main/resources/static/image/flag/vu.png differ diff --git a/src/main/resources/static/image/flag/wales.png b/src/main/resources/static/image/flag/wales.png new file mode 100644 index 0000000..e0d7cee Binary files /dev/null and b/src/main/resources/static/image/flag/wales.png differ diff --git a/src/main/resources/static/image/flag/wf.png b/src/main/resources/static/image/flag/wf.png new file mode 100644 index 0000000..9f95587 Binary files /dev/null and b/src/main/resources/static/image/flag/wf.png differ diff --git a/src/main/resources/static/image/flag/ws.png b/src/main/resources/static/image/flag/ws.png new file mode 100644 index 0000000..c169508 Binary files /dev/null and b/src/main/resources/static/image/flag/ws.png differ diff --git a/src/main/resources/static/image/flag/ye.png b/src/main/resources/static/image/flag/ye.png new file mode 100644 index 0000000..468dfad Binary files /dev/null and b/src/main/resources/static/image/flag/ye.png differ diff --git a/src/main/resources/static/image/flag/yt.png b/src/main/resources/static/image/flag/yt.png new file mode 100644 index 0000000..c298f37 Binary files /dev/null and b/src/main/resources/static/image/flag/yt.png differ diff --git a/src/main/resources/static/image/flag/za.png b/src/main/resources/static/image/flag/za.png new file mode 100644 index 0000000..57c58e2 Binary files /dev/null and b/src/main/resources/static/image/flag/za.png differ diff --git a/src/main/resources/static/image/flag/zm.png b/src/main/resources/static/image/flag/zm.png new file mode 100644 index 0000000..c25b07b Binary files /dev/null and b/src/main/resources/static/image/flag/zm.png differ diff --git a/src/main/resources/static/image/flag/zw.png b/src/main/resources/static/image/flag/zw.png new file mode 100644 index 0000000..53c9725 Binary files /dev/null and b/src/main/resources/static/image/flag/zw.png differ diff --git a/src/main/resources/static/image/folder/alarms.png b/src/main/resources/static/image/folder/alarms.png new file mode 100644 index 0000000..128567d Binary files /dev/null and b/src/main/resources/static/image/folder/alarms.png differ diff --git a/src/main/resources/static/image/folder/android.png b/src/main/resources/static/image/folder/android.png new file mode 100644 index 0000000..ff89855 Binary files /dev/null and b/src/main/resources/static/image/folder/android.png differ diff --git a/src/main/resources/static/image/folder/book.png b/src/main/resources/static/image/folder/book.png new file mode 100644 index 0000000..0b2becd Binary files /dev/null and b/src/main/resources/static/image/folder/book.png differ diff --git a/src/main/resources/static/image/folder/dcim.png b/src/main/resources/static/image/folder/dcim.png new file mode 100644 index 0000000..4d14aae Binary files /dev/null and b/src/main/resources/static/image/folder/dcim.png differ diff --git a/src/main/resources/static/image/folder/documents.png b/src/main/resources/static/image/folder/documents.png new file mode 100644 index 0000000..9233e0f Binary files /dev/null and b/src/main/resources/static/image/folder/documents.png differ diff --git a/src/main/resources/static/image/folder/download.png b/src/main/resources/static/image/folder/download.png new file mode 100644 index 0000000..b1311ca Binary files /dev/null and b/src/main/resources/static/image/folder/download.png differ diff --git a/src/main/resources/static/image/folder/movies.png b/src/main/resources/static/image/folder/movies.png new file mode 100644 index 0000000..dcd8362 Binary files /dev/null and b/src/main/resources/static/image/folder/movies.png differ diff --git a/src/main/resources/static/image/folder/music.png b/src/main/resources/static/image/folder/music.png new file mode 100644 index 0000000..73ff3b1 Binary files /dev/null and b/src/main/resources/static/image/folder/music.png differ diff --git a/src/main/resources/static/image/folder/normal.png b/src/main/resources/static/image/folder/normal.png new file mode 100644 index 0000000..d4a4558 Binary files /dev/null and b/src/main/resources/static/image/folder/normal.png differ diff --git a/src/main/resources/static/image/folder/notifications.png b/src/main/resources/static/image/folder/notifications.png new file mode 100644 index 0000000..b629222 Binary files /dev/null and b/src/main/resources/static/image/folder/notifications.png differ diff --git a/src/main/resources/static/image/folder/option.png b/src/main/resources/static/image/folder/option.png new file mode 100644 index 0000000..c91e688 Binary files /dev/null and b/src/main/resources/static/image/folder/option.png differ diff --git a/src/main/resources/static/image/folder/pictures.png b/src/main/resources/static/image/folder/pictures.png new file mode 100644 index 0000000..6356ce5 Binary files /dev/null and b/src/main/resources/static/image/folder/pictures.png differ diff --git a/src/main/resources/static/image/folder/podcasts.png b/src/main/resources/static/image/folder/podcasts.png new file mode 100644 index 0000000..1d1f2d3 Binary files /dev/null and b/src/main/resources/static/image/folder/podcasts.png differ diff --git a/src/main/resources/static/image/folder/private.png b/src/main/resources/static/image/folder/private.png new file mode 100644 index 0000000..64ae457 Binary files /dev/null and b/src/main/resources/static/image/folder/private.png differ diff --git a/src/main/resources/static/image/folder/ringtones.png b/src/main/resources/static/image/folder/ringtones.png new file mode 100644 index 0000000..a2cb0da Binary files /dev/null and b/src/main/resources/static/image/folder/ringtones.png differ diff --git a/src/main/resources/static/image/folder/system.png b/src/main/resources/static/image/folder/system.png new file mode 100644 index 0000000..55d67a8 Binary files /dev/null and b/src/main/resources/static/image/folder/system.png differ diff --git a/src/main/resources/static/image/folder/torrent.png b/src/main/resources/static/image/folder/torrent.png new file mode 100644 index 0000000..1c14ec7 Binary files /dev/null and b/src/main/resources/static/image/folder/torrent.png differ diff --git a/src/main/resources/static/image/folder/upload.png b/src/main/resources/static/image/folder/upload.png new file mode 100644 index 0000000..4b1f9ef Binary files /dev/null and b/src/main/resources/static/image/folder/upload.png differ diff --git a/src/main/resources/static/image/folder/windows.png b/src/main/resources/static/image/folder/windows.png new file mode 100644 index 0000000..d46bf3d Binary files /dev/null and b/src/main/resources/static/image/folder/windows.png differ diff --git a/src/main/resources/static/image/icon/bar.svg b/src/main/resources/static/image/icon/bar.svg new file mode 100644 index 0000000..23f0ce1 --- /dev/null +++ b/src/main/resources/static/image/icon/bar.svg @@ -0,0 +1,18 @@ + + + + icon/bar + Created with Sketch. + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/image/icon/geomap.svg b/src/main/resources/static/image/icon/geomap.svg new file mode 100644 index 0000000..1c377db --- /dev/null +++ b/src/main/resources/static/image/icon/geomap.svg @@ -0,0 +1,18 @@ + + + + icon/geomap + Created with Sketch. + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/image/icon/line.svg b/src/main/resources/static/image/icon/line.svg new file mode 100644 index 0000000..f9afd5c --- /dev/null +++ b/src/main/resources/static/image/icon/line.svg @@ -0,0 +1,18 @@ + + + + icon/line + Created with Sketch. + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/image/icon/pie.svg b/src/main/resources/static/image/icon/pie.svg new file mode 100644 index 0000000..f98eb05 --- /dev/null +++ b/src/main/resources/static/image/icon/pie.svg @@ -0,0 +1,18 @@ + + + + icon/pie + Created with Sketch. + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/image/icon/profileUnknown.png b/src/main/resources/static/image/icon/profileUnknown.png new file mode 100644 index 0000000..a0d223a Binary files /dev/null and b/src/main/resources/static/image/icon/profileUnknown.png differ diff --git a/src/main/resources/static/image/icon/siteUnknown.png b/src/main/resources/static/image/icon/siteUnknown.png new file mode 100644 index 0000000..b5ebcfe Binary files /dev/null and b/src/main/resources/static/image/icon/siteUnknown.png differ diff --git a/src/main/resources/static/image/icon/table.svg b/src/main/resources/static/image/icon/table.svg new file mode 100644 index 0000000..96d9133 --- /dev/null +++ b/src/main/resources/static/image/icon/table.svg @@ -0,0 +1,18 @@ + + + + icon/table + Created with Sketch. + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/static/image/logo.png b/src/main/resources/static/image/logo.png new file mode 100644 index 0000000..38c6e74 Binary files /dev/null and b/src/main/resources/static/image/logo.png differ diff --git a/src/main/resources/static/image/logo.svg b/src/main/resources/static/image/logo.svg new file mode 100644 index 0000000..cfaf187 --- /dev/null +++ b/src/main/resources/static/image/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/resources/static/image/logo_lite.png b/src/main/resources/static/image/logo_lite.png new file mode 100644 index 0000000..ecd06db Binary files /dev/null and b/src/main/resources/static/image/logo_lite.png differ diff --git a/src/main/resources/static/image/mime/_blank.png b/src/main/resources/static/image/mime/_blank.png new file mode 100644 index 0000000..ae53a4e Binary files /dev/null and b/src/main/resources/static/image/mime/_blank.png differ diff --git a/src/main/resources/static/image/mime/_page.png b/src/main/resources/static/image/mime/_page.png new file mode 100644 index 0000000..b8d155e Binary files /dev/null and b/src/main/resources/static/image/mime/_page.png differ diff --git a/src/main/resources/static/image/mime/aac.png b/src/main/resources/static/image/mime/aac.png new file mode 100644 index 0000000..200db51 Binary files /dev/null and b/src/main/resources/static/image/mime/aac.png differ diff --git a/src/main/resources/static/image/mime/ai.png b/src/main/resources/static/image/mime/ai.png new file mode 100644 index 0000000..c1810f5 Binary files /dev/null and b/src/main/resources/static/image/mime/ai.png differ diff --git a/src/main/resources/static/image/mime/aiff.png b/src/main/resources/static/image/mime/aiff.png new file mode 100644 index 0000000..f9f1faf Binary files /dev/null and b/src/main/resources/static/image/mime/aiff.png differ diff --git a/src/main/resources/static/image/mime/apk.png b/src/main/resources/static/image/mime/apk.png new file mode 100644 index 0000000..700bb19 Binary files /dev/null and b/src/main/resources/static/image/mime/apk.png differ diff --git a/src/main/resources/static/image/mime/avi.png b/src/main/resources/static/image/mime/avi.png new file mode 100644 index 0000000..6ddfcea Binary files /dev/null and b/src/main/resources/static/image/mime/avi.png differ diff --git a/src/main/resources/static/image/mime/bmp.png b/src/main/resources/static/image/mime/bmp.png new file mode 100644 index 0000000..0efcc32 Binary files /dev/null and b/src/main/resources/static/image/mime/bmp.png differ diff --git a/src/main/resources/static/image/mime/c.png b/src/main/resources/static/image/mime/c.png new file mode 100644 index 0000000..249e6c7 Binary files /dev/null and b/src/main/resources/static/image/mime/c.png differ diff --git a/src/main/resources/static/image/mime/cpp.png b/src/main/resources/static/image/mime/cpp.png new file mode 100644 index 0000000..0a6cd8b Binary files /dev/null and b/src/main/resources/static/image/mime/cpp.png differ diff --git a/src/main/resources/static/image/mime/css.png b/src/main/resources/static/image/mime/css.png new file mode 100644 index 0000000..8035b9d Binary files /dev/null and b/src/main/resources/static/image/mime/css.png differ diff --git a/src/main/resources/static/image/mime/dat.png b/src/main/resources/static/image/mime/dat.png new file mode 100644 index 0000000..971e364 Binary files /dev/null and b/src/main/resources/static/image/mime/dat.png differ diff --git a/src/main/resources/static/image/mime/dmg.png b/src/main/resources/static/image/mime/dmg.png new file mode 100644 index 0000000..94a38ae Binary files /dev/null and b/src/main/resources/static/image/mime/dmg.png differ diff --git a/src/main/resources/static/image/mime/doc.png b/src/main/resources/static/image/mime/doc.png new file mode 100644 index 0000000..aff8234 Binary files /dev/null and b/src/main/resources/static/image/mime/doc.png differ diff --git a/src/main/resources/static/image/mime/docx.png b/src/main/resources/static/image/mime/docx.png new file mode 100644 index 0000000..aff8234 Binary files /dev/null and b/src/main/resources/static/image/mime/docx.png differ diff --git a/src/main/resources/static/image/mime/dotx.png b/src/main/resources/static/image/mime/dotx.png new file mode 100644 index 0000000..b0220e3 Binary files /dev/null and b/src/main/resources/static/image/mime/dotx.png differ diff --git a/src/main/resources/static/image/mime/dwg.png b/src/main/resources/static/image/mime/dwg.png new file mode 100644 index 0000000..de4fe53 Binary files /dev/null and b/src/main/resources/static/image/mime/dwg.png differ diff --git a/src/main/resources/static/image/mime/dxf.png b/src/main/resources/static/image/mime/dxf.png new file mode 100644 index 0000000..2ed2465 Binary files /dev/null and b/src/main/resources/static/image/mime/dxf.png differ diff --git a/src/main/resources/static/image/mime/eps.png b/src/main/resources/static/image/mime/eps.png new file mode 100644 index 0000000..cc32db8 Binary files /dev/null and b/src/main/resources/static/image/mime/eps.png differ diff --git a/src/main/resources/static/image/mime/exe.png b/src/main/resources/static/image/mime/exe.png new file mode 100644 index 0000000..60e5f6b Binary files /dev/null and b/src/main/resources/static/image/mime/exe.png differ diff --git a/src/main/resources/static/image/mime/flv.png b/src/main/resources/static/image/mime/flv.png new file mode 100644 index 0000000..73bc4cc Binary files /dev/null and b/src/main/resources/static/image/mime/flv.png differ diff --git a/src/main/resources/static/image/mime/gif.png b/src/main/resources/static/image/mime/gif.png new file mode 100644 index 0000000..07e601f Binary files /dev/null and b/src/main/resources/static/image/mime/gif.png differ diff --git a/src/main/resources/static/image/mime/h.png b/src/main/resources/static/image/mime/h.png new file mode 100644 index 0000000..f5cc5e5 Binary files /dev/null and b/src/main/resources/static/image/mime/h.png differ diff --git a/src/main/resources/static/image/mime/hpp.png b/src/main/resources/static/image/mime/hpp.png new file mode 100644 index 0000000..ddcc8bf Binary files /dev/null and b/src/main/resources/static/image/mime/hpp.png differ diff --git a/src/main/resources/static/image/mime/html.png b/src/main/resources/static/image/mime/html.png new file mode 100644 index 0000000..454cd9f Binary files /dev/null and b/src/main/resources/static/image/mime/html.png differ diff --git a/src/main/resources/static/image/mime/ics.png b/src/main/resources/static/image/mime/ics.png new file mode 100644 index 0000000..7a0f5c0 Binary files /dev/null and b/src/main/resources/static/image/mime/ics.png differ diff --git a/src/main/resources/static/image/mime/iso.png b/src/main/resources/static/image/mime/iso.png new file mode 100644 index 0000000..729fa7f Binary files /dev/null and b/src/main/resources/static/image/mime/iso.png differ diff --git a/src/main/resources/static/image/mime/jar.png b/src/main/resources/static/image/mime/jar.png new file mode 100644 index 0000000..0d46a4a Binary files /dev/null and b/src/main/resources/static/image/mime/jar.png differ diff --git a/src/main/resources/static/image/mime/java.png b/src/main/resources/static/image/mime/java.png new file mode 100644 index 0000000..0d46a4a Binary files /dev/null and b/src/main/resources/static/image/mime/java.png differ diff --git a/src/main/resources/static/image/mime/jpeg.png b/src/main/resources/static/image/mime/jpeg.png new file mode 100644 index 0000000..4262c4e Binary files /dev/null and b/src/main/resources/static/image/mime/jpeg.png differ diff --git a/src/main/resources/static/image/mime/jpg.png b/src/main/resources/static/image/mime/jpg.png new file mode 100644 index 0000000..4262c4e Binary files /dev/null and b/src/main/resources/static/image/mime/jpg.png differ diff --git a/src/main/resources/static/image/mime/js.png b/src/main/resources/static/image/mime/js.png new file mode 100644 index 0000000..507661c Binary files /dev/null and b/src/main/resources/static/image/mime/js.png differ diff --git a/src/main/resources/static/image/mime/json.png b/src/main/resources/static/image/mime/json.png new file mode 100644 index 0000000..525826a Binary files /dev/null and b/src/main/resources/static/image/mime/json.png differ diff --git a/src/main/resources/static/image/mime/key.png b/src/main/resources/static/image/mime/key.png new file mode 100644 index 0000000..44ab47e Binary files /dev/null and b/src/main/resources/static/image/mime/key.png differ diff --git a/src/main/resources/static/image/mime/less.png b/src/main/resources/static/image/mime/less.png new file mode 100644 index 0000000..2d7b56f Binary files /dev/null and b/src/main/resources/static/image/mime/less.png differ diff --git a/src/main/resources/static/image/mime/mid.png b/src/main/resources/static/image/mime/mid.png new file mode 100644 index 0000000..fc50598 Binary files /dev/null and b/src/main/resources/static/image/mime/mid.png differ diff --git a/src/main/resources/static/image/mime/milock.png b/src/main/resources/static/image/mime/milock.png new file mode 100644 index 0000000..c047e96 Binary files /dev/null and b/src/main/resources/static/image/mime/milock.png differ diff --git a/src/main/resources/static/image/mime/mp3.png b/src/main/resources/static/image/mime/mp3.png new file mode 100644 index 0000000..568a51c Binary files /dev/null and b/src/main/resources/static/image/mime/mp3.png differ diff --git a/src/main/resources/static/image/mime/mp4.png b/src/main/resources/static/image/mime/mp4.png new file mode 100644 index 0000000..c83c923 Binary files /dev/null and b/src/main/resources/static/image/mime/mp4.png differ diff --git a/src/main/resources/static/image/mime/mpg.png b/src/main/resources/static/image/mime/mpg.png new file mode 100644 index 0000000..e106159 Binary files /dev/null and b/src/main/resources/static/image/mime/mpg.png differ diff --git a/src/main/resources/static/image/mime/must.png b/src/main/resources/static/image/mime/must.png new file mode 100644 index 0000000..9fcfced Binary files /dev/null and b/src/main/resources/static/image/mime/must.png differ diff --git a/src/main/resources/static/image/mime/odf.png b/src/main/resources/static/image/mime/odf.png new file mode 100644 index 0000000..8173771 Binary files /dev/null and b/src/main/resources/static/image/mime/odf.png differ diff --git a/src/main/resources/static/image/mime/ods.png b/src/main/resources/static/image/mime/ods.png new file mode 100644 index 0000000..a3c5cc2 Binary files /dev/null and b/src/main/resources/static/image/mime/ods.png differ diff --git a/src/main/resources/static/image/mime/odt.png b/src/main/resources/static/image/mime/odt.png new file mode 100644 index 0000000..1e72fd4 Binary files /dev/null and b/src/main/resources/static/image/mime/odt.png differ diff --git a/src/main/resources/static/image/mime/otp.png b/src/main/resources/static/image/mime/otp.png new file mode 100644 index 0000000..b419dc6 Binary files /dev/null and b/src/main/resources/static/image/mime/otp.png differ diff --git a/src/main/resources/static/image/mime/ots.png b/src/main/resources/static/image/mime/ots.png new file mode 100644 index 0000000..712b039 Binary files /dev/null and b/src/main/resources/static/image/mime/ots.png differ diff --git a/src/main/resources/static/image/mime/ott.png b/src/main/resources/static/image/mime/ott.png new file mode 100644 index 0000000..2540efd Binary files /dev/null and b/src/main/resources/static/image/mime/ott.png differ diff --git a/src/main/resources/static/image/mime/pdf.png b/src/main/resources/static/image/mime/pdf.png new file mode 100644 index 0000000..b288c3f Binary files /dev/null and b/src/main/resources/static/image/mime/pdf.png differ diff --git a/src/main/resources/static/image/mime/php.png b/src/main/resources/static/image/mime/php.png new file mode 100644 index 0000000..615591e Binary files /dev/null and b/src/main/resources/static/image/mime/php.png differ diff --git a/src/main/resources/static/image/mime/png.png b/src/main/resources/static/image/mime/png.png new file mode 100644 index 0000000..374333c Binary files /dev/null and b/src/main/resources/static/image/mime/png.png differ diff --git a/src/main/resources/static/image/mime/ppt.png b/src/main/resources/static/image/mime/ppt.png new file mode 100644 index 0000000..42f8895 Binary files /dev/null and b/src/main/resources/static/image/mime/ppt.png differ diff --git a/src/main/resources/static/image/mime/pptx.png b/src/main/resources/static/image/mime/pptx.png new file mode 100644 index 0000000..42f8895 Binary files /dev/null and b/src/main/resources/static/image/mime/pptx.png differ diff --git a/src/main/resources/static/image/mime/psd.png b/src/main/resources/static/image/mime/psd.png new file mode 100644 index 0000000..4351dd3 Binary files /dev/null and b/src/main/resources/static/image/mime/psd.png differ diff --git a/src/main/resources/static/image/mime/py.png b/src/main/resources/static/image/mime/py.png new file mode 100644 index 0000000..9e5668f Binary files /dev/null and b/src/main/resources/static/image/mime/py.png differ diff --git a/src/main/resources/static/image/mime/qt.png b/src/main/resources/static/image/mime/qt.png new file mode 100644 index 0000000..4deac47 Binary files /dev/null and b/src/main/resources/static/image/mime/qt.png differ diff --git a/src/main/resources/static/image/mime/rar.png b/src/main/resources/static/image/mime/rar.png new file mode 100644 index 0000000..ad4b879 Binary files /dev/null and b/src/main/resources/static/image/mime/rar.png differ diff --git a/src/main/resources/static/image/mime/rb.png b/src/main/resources/static/image/mime/rb.png new file mode 100644 index 0000000..5b4a52b Binary files /dev/null and b/src/main/resources/static/image/mime/rb.png differ diff --git a/src/main/resources/static/image/mime/rtf.png b/src/main/resources/static/image/mime/rtf.png new file mode 100644 index 0000000..99510b9 Binary files /dev/null and b/src/main/resources/static/image/mime/rtf.png differ diff --git a/src/main/resources/static/image/mime/sass.png b/src/main/resources/static/image/mime/sass.png new file mode 100644 index 0000000..27ebf76 Binary files /dev/null and b/src/main/resources/static/image/mime/sass.png differ diff --git a/src/main/resources/static/image/mime/scss.png b/src/main/resources/static/image/mime/scss.png new file mode 100644 index 0000000..33b47f4 Binary files /dev/null and b/src/main/resources/static/image/mime/scss.png differ diff --git a/src/main/resources/static/image/mime/sql.png b/src/main/resources/static/image/mime/sql.png new file mode 100644 index 0000000..1742560 Binary files /dev/null and b/src/main/resources/static/image/mime/sql.png differ diff --git a/src/main/resources/static/image/mime/tga.png b/src/main/resources/static/image/mime/tga.png new file mode 100644 index 0000000..2a97d3d Binary files /dev/null and b/src/main/resources/static/image/mime/tga.png differ diff --git a/src/main/resources/static/image/mime/tgz.png b/src/main/resources/static/image/mime/tgz.png new file mode 100644 index 0000000..2572e1f Binary files /dev/null and b/src/main/resources/static/image/mime/tgz.png differ diff --git a/src/main/resources/static/image/mime/tiff.png b/src/main/resources/static/image/mime/tiff.png new file mode 100644 index 0000000..a44d071 Binary files /dev/null and b/src/main/resources/static/image/mime/tiff.png differ diff --git a/src/main/resources/static/image/mime/txt.png b/src/main/resources/static/image/mime/txt.png new file mode 100644 index 0000000..36c466c Binary files /dev/null and b/src/main/resources/static/image/mime/txt.png differ diff --git a/src/main/resources/static/image/mime/war.png b/src/main/resources/static/image/mime/war.png new file mode 100644 index 0000000..0d46a4a Binary files /dev/null and b/src/main/resources/static/image/mime/war.png differ diff --git a/src/main/resources/static/image/mime/wav.png b/src/main/resources/static/image/mime/wav.png new file mode 100644 index 0000000..523b9b6 Binary files /dev/null and b/src/main/resources/static/image/mime/wav.png differ diff --git a/src/main/resources/static/image/mime/xls.png b/src/main/resources/static/image/mime/xls.png new file mode 100644 index 0000000..c66931c Binary files /dev/null and b/src/main/resources/static/image/mime/xls.png differ diff --git a/src/main/resources/static/image/mime/xlsx.png b/src/main/resources/static/image/mime/xlsx.png new file mode 100644 index 0000000..5dd5905 Binary files /dev/null and b/src/main/resources/static/image/mime/xlsx.png differ diff --git a/src/main/resources/static/image/mime/xml.png b/src/main/resources/static/image/mime/xml.png new file mode 100644 index 0000000..9fcfced Binary files /dev/null and b/src/main/resources/static/image/mime/xml.png differ diff --git a/src/main/resources/static/image/mime/yml.png b/src/main/resources/static/image/mime/yml.png new file mode 100644 index 0000000..373f983 Binary files /dev/null and b/src/main/resources/static/image/mime/yml.png differ diff --git a/src/main/resources/static/image/mime/zip.png b/src/main/resources/static/image/mime/zip.png new file mode 100644 index 0000000..238768c Binary files /dev/null and b/src/main/resources/static/image/mime/zip.png differ diff --git a/src/main/resources/static/image/platform/bg_GeminiPro.png b/src/main/resources/static/image/platform/bg_GeminiPro.png new file mode 100644 index 0000000..c545a82 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_GeminiPro.png differ diff --git a/src/main/resources/static/image/platform/bg_ares.png b/src/main/resources/static/image/platform/bg_ares.png new file mode 100644 index 0000000..b6fd745 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_ares.png differ diff --git a/src/main/resources/static/image/platform/bg_caddie.png b/src/main/resources/static/image/platform/bg_caddie.png new file mode 100644 index 0000000..667d011 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_caddie.png differ diff --git a/src/main/resources/static/image/platform/bg_chiron.png b/src/main/resources/static/image/platform/bg_chiron.png new file mode 100644 index 0000000..2da0e58 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_chiron.png differ diff --git a/src/main/resources/static/image/platform/bg_chiron_pro.png b/src/main/resources/static/image/platform/bg_chiron_pro.png new file mode 100644 index 0000000..2da0e58 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_chiron_pro.png differ diff --git a/src/main/resources/static/image/platform/bg_evo.png b/src/main/resources/static/image/platform/bg_evo.png new file mode 100644 index 0000000..6e324ee Binary files /dev/null and b/src/main/resources/static/image/platform/bg_evo.png differ diff --git a/src/main/resources/static/image/platform/bg_gaia.png b/src/main/resources/static/image/platform/bg_gaia.png new file mode 100644 index 0000000..b6fd745 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_gaia.png differ diff --git a/src/main/resources/static/image/platform/bg_gemini.png b/src/main/resources/static/image/platform/bg_gemini.png new file mode 100644 index 0000000..c545a82 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_gemini.png differ diff --git a/src/main/resources/static/image/platform/bg_gemini_pro.png b/src/main/resources/static/image/platform/bg_gemini_pro.png new file mode 100644 index 0000000..c545a82 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_gemini_pro.png differ diff --git a/src/main/resources/static/image/platform/bg_hera.png b/src/main/resources/static/image/platform/bg_hera.png new file mode 100644 index 0000000..774e599 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_hera.png differ diff --git a/src/main/resources/static/image/platform/bg_hera_pro.png b/src/main/resources/static/image/platform/bg_hera_pro.png new file mode 100644 index 0000000..774e599 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_hera_pro.png differ diff --git a/src/main/resources/static/image/platform/bg_ma70.png b/src/main/resources/static/image/platform/bg_ma70.png new file mode 100644 index 0000000..3e85a32 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_ma70.png differ diff --git a/src/main/resources/static/image/platform/bg_phaeton.png b/src/main/resources/static/image/platform/bg_phaeton.png new file mode 100644 index 0000000..d97cddc Binary files /dev/null and b/src/main/resources/static/image/platform/bg_phaeton.png differ diff --git a/src/main/resources/static/image/platform/bg_prometheus.png b/src/main/resources/static/image/platform/bg_prometheus.png new file mode 100644 index 0000000..5abd4b0 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_prometheus.png differ diff --git a/src/main/resources/static/image/platform/bg_racing.png b/src/main/resources/static/image/platform/bg_racing.png new file mode 100644 index 0000000..b6625e4 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_racing.png differ diff --git a/src/main/resources/static/image/platform/bg_sm6150.png b/src/main/resources/static/image/platform/bg_sm6150.png new file mode 100644 index 0000000..7652e5e Binary files /dev/null and b/src/main/resources/static/image/platform/bg_sm6150.png differ diff --git a/src/main/resources/static/image/platform/bg_sprint.png b/src/main/resources/static/image/platform/bg_sprint.png new file mode 100644 index 0000000..c1efa21 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_sprint.png differ diff --git a/src/main/resources/static/image/platform/bg_surfing_pro.png b/src/main/resources/static/image/platform/bg_surfing_pro.png new file mode 100644 index 0000000..3b227f8 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_surfing_pro.png differ diff --git a/src/main/resources/static/image/platform/bg_tulkas.png b/src/main/resources/static/image/platform/bg_tulkas.png new file mode 100644 index 0000000..667d011 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_tulkas.png differ diff --git a/src/main/resources/static/image/platform/bg_tulkas2.png b/src/main/resources/static/image/platform/bg_tulkas2.png new file mode 100644 index 0000000..667d011 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_tulkas2.png differ diff --git a/src/main/resources/static/image/platform/bg_tulkas_pro.png b/src/main/resources/static/image/platform/bg_tulkas_pro.png new file mode 100644 index 0000000..9e485d4 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_tulkas_pro.png differ diff --git a/src/main/resources/static/image/platform/bg_ulmo.png b/src/main/resources/static/image/platform/bg_ulmo.png new file mode 100644 index 0000000..3e85a32 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_ulmo.png differ diff --git a/src/main/resources/static/image/platform/bg_ulmo_pro.png b/src/main/resources/static/image/platform/bg_ulmo_pro.png new file mode 100644 index 0000000..3e85a32 Binary files /dev/null and b/src/main/resources/static/image/platform/bg_ulmo_pro.png differ diff --git a/src/main/resources/static/image/platform/ic_device_GeminiPro.png b/src/main/resources/static/image/platform/ic_device_GeminiPro.png new file mode 100644 index 0000000..aa156c0 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_GeminiPro.png differ diff --git a/src/main/resources/static/image/platform/ic_device_aries.png b/src/main/resources/static/image/platform/ic_device_aries.png new file mode 100644 index 0000000..768a947 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_aries.png differ diff --git a/src/main/resources/static/image/platform/ic_device_caddie.png b/src/main/resources/static/image/platform/ic_device_caddie.png new file mode 100644 index 0000000..b3600d5 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_caddie.png differ diff --git a/src/main/resources/static/image/platform/ic_device_chiron.png b/src/main/resources/static/image/platform/ic_device_chiron.png new file mode 100644 index 0000000..52d7e44 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_chiron.png differ diff --git a/src/main/resources/static/image/platform/ic_device_chiron_pro.png b/src/main/resources/static/image/platform/ic_device_chiron_pro.png new file mode 100644 index 0000000..52d7e44 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_chiron_pro.png differ diff --git a/src/main/resources/static/image/platform/ic_device_evo.png b/src/main/resources/static/image/platform/ic_device_evo.png new file mode 100644 index 0000000..3f26f62 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_evo.png differ diff --git a/src/main/resources/static/image/platform/ic_device_gaia.png b/src/main/resources/static/image/platform/ic_device_gaia.png new file mode 100644 index 0000000..b4cb744 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_gaia.png differ diff --git a/src/main/resources/static/image/platform/ic_device_gemini.png b/src/main/resources/static/image/platform/ic_device_gemini.png new file mode 100644 index 0000000..aa156c0 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_gemini.png differ diff --git a/src/main/resources/static/image/platform/ic_device_gemini_pro.png b/src/main/resources/static/image/platform/ic_device_gemini_pro.png new file mode 100644 index 0000000..aa156c0 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_gemini_pro.png differ diff --git a/src/main/resources/static/image/platform/ic_device_hera.png b/src/main/resources/static/image/platform/ic_device_hera.png new file mode 100644 index 0000000..70c8688 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_hera.png differ diff --git a/src/main/resources/static/image/platform/ic_device_hera_pro.png b/src/main/resources/static/image/platform/ic_device_hera_pro.png new file mode 100644 index 0000000..70c8688 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_hera_pro.png differ diff --git a/src/main/resources/static/image/platform/ic_device_ma70.png b/src/main/resources/static/image/platform/ic_device_ma70.png new file mode 100644 index 0000000..fd8b0d7 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_ma70.png differ diff --git a/src/main/resources/static/image/platform/ic_device_phaeton.png b/src/main/resources/static/image/platform/ic_device_phaeton.png new file mode 100644 index 0000000..14cca69 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_phaeton.png differ diff --git a/src/main/resources/static/image/platform/ic_device_prometheus.png b/src/main/resources/static/image/platform/ic_device_prometheus.png new file mode 100644 index 0000000..54fbcb3 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_prometheus.png differ diff --git a/src/main/resources/static/image/platform/ic_device_racing.png b/src/main/resources/static/image/platform/ic_device_racing.png new file mode 100644 index 0000000..09947b5 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_racing.png differ diff --git a/src/main/resources/static/image/platform/ic_device_sm6150.png b/src/main/resources/static/image/platform/ic_device_sm6150.png new file mode 100644 index 0000000..6d4f2ff Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_sm6150.png differ diff --git a/src/main/resources/static/image/platform/ic_device_sprint.png b/src/main/resources/static/image/platform/ic_device_sprint.png new file mode 100644 index 0000000..fd26735 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_sprint.png differ diff --git a/src/main/resources/static/image/platform/ic_device_surfing_pro.png b/src/main/resources/static/image/platform/ic_device_surfing_pro.png new file mode 100644 index 0000000..5d125d2 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_surfing_pro.png differ diff --git a/src/main/resources/static/image/platform/ic_device_tulkas.png b/src/main/resources/static/image/platform/ic_device_tulkas.png new file mode 100644 index 0000000..b3600d5 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_tulkas.png differ diff --git a/src/main/resources/static/image/platform/ic_device_tulkas2.png b/src/main/resources/static/image/platform/ic_device_tulkas2.png new file mode 100644 index 0000000..b3600d5 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_tulkas2.png differ diff --git a/src/main/resources/static/image/platform/ic_device_tulkas_pro.png b/src/main/resources/static/image/platform/ic_device_tulkas_pro.png new file mode 100644 index 0000000..a2db52c Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_tulkas_pro.png differ diff --git a/src/main/resources/static/image/platform/ic_device_ulmo.png b/src/main/resources/static/image/platform/ic_device_ulmo.png new file mode 100644 index 0000000..fd8b0d7 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_ulmo.png differ diff --git a/src/main/resources/static/image/platform/ic_device_ulmo_pro.png b/src/main/resources/static/image/platform/ic_device_ulmo_pro.png new file mode 100644 index 0000000..fd8b0d7 Binary files /dev/null and b/src/main/resources/static/image/platform/ic_device_ulmo_pro.png differ diff --git a/src/main/resources/static/image/platform/unknown_device.png b/src/main/resources/static/image/platform/unknown_device.png new file mode 100644 index 0000000..5df9313 Binary files /dev/null and b/src/main/resources/static/image/platform/unknown_device.png differ diff --git a/src/main/resources/static/module/Waves/waves.css b/src/main/resources/static/module/Waves/waves.css new file mode 100644 index 0000000..0a28241 --- /dev/null +++ b/src/main/resources/static/module/Waves/waves.css @@ -0,0 +1,136 @@ +/*! + * Waves v0.7.5 + * http://fian.my.id/Waves + * + * Copyright 2014-2016 Alfiana E. Sibuea and other contributors + * Released under the MIT license + * https://github.com/fians/Waves/blob/master/LICENSE + */ +.waves-effect { + position: relative; + cursor: pointer; + display: inline-block; + overflow: hidden; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + -webkit-tap-highlight-color: transparent; +} +.waves-effect .waves-ripple { + position: absolute; + border-radius: 50%; + width: 100px; + height: 100px; + margin-top: -50px; + margin-left: -50px; + opacity: 0; + background: rgba(0, 0, 0, 0.2); + background: -webkit-radial-gradient(rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0.3) 40%, rgba(0, 0, 0, 0.4) 50%, rgba(0, 0, 0, 0.5) 60%, rgba(255, 255, 255, 0) 70%); + background: -o-radial-gradient(rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0.3) 40%, rgba(0, 0, 0, 0.4) 50%, rgba(0, 0, 0, 0.5) 60%, rgba(255, 255, 255, 0) 70%); + background: -moz-radial-gradient(rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0.3) 40%, rgba(0, 0, 0, 0.4) 50%, rgba(0, 0, 0, 0.5) 60%, rgba(255, 255, 255, 0) 70%); + background: radial-gradient(rgba(0, 0, 0, 0.2) 0, rgba(0, 0, 0, 0.3) 40%, rgba(0, 0, 0, 0.4) 50%, rgba(0, 0, 0, 0.5) 60%, rgba(255, 255, 255, 0) 70%); + -webkit-transition: all 0.5s ease-out; + -moz-transition: all 0.5s ease-out; + -o-transition: all 0.5s ease-out; + transition: all 0.5s ease-out; + -webkit-transition-property: -webkit-transform, opacity; + -moz-transition-property: -moz-transform, opacity; + -o-transition-property: -o-transform, opacity; + transition-property: transform, opacity; + -webkit-transform: scale(0) translate(0, 0); + -moz-transform: scale(0) translate(0, 0); + -ms-transform: scale(0) translate(0, 0); + -o-transform: scale(0) translate(0, 0); + transform: scale(0) translate(0, 0); + pointer-events: none; +} +.waves-effect.waves-light .waves-ripple { + background: rgba(255, 255, 255, 0.4); + background: -webkit-radial-gradient(rgba(255, 255, 255, 0.2) 0, rgba(255, 255, 255, 0.3) 40%, rgba(255, 255, 255, 0.4) 50%, rgba(255, 255, 255, 0.5) 60%, rgba(255, 255, 255, 0) 70%); + background: -o-radial-gradient(rgba(255, 255, 255, 0.2) 0, rgba(255, 255, 255, 0.3) 40%, rgba(255, 255, 255, 0.4) 50%, rgba(255, 255, 255, 0.5) 60%, rgba(255, 255, 255, 0) 70%); + background: -moz-radial-gradient(rgba(255, 255, 255, 0.2) 0, rgba(255, 255, 255, 0.3) 40%, rgba(255, 255, 255, 0.4) 50%, rgba(255, 255, 255, 0.5) 60%, rgba(255, 255, 255, 0) 70%); + background: radial-gradient(rgba(255, 255, 255, 0.2) 0, rgba(255, 255, 255, 0.3) 40%, rgba(255, 255, 255, 0.4) 50%, rgba(255, 255, 255, 0.5) 60%, rgba(255, 255, 255, 0) 70%); +} +.waves-effect.waves-classic .waves-ripple { + background: rgba(0, 0, 0, 0.2); +} +.waves-effect.waves-classic.waves-light .waves-ripple { + background: rgba(255, 255, 255, 0.4); +} +.waves-notransition { + -webkit-transition: none !important; + -moz-transition: none !important; + -o-transition: none !important; + transition: none !important; +} +.waves-button, +.waves-circle { + -webkit-transform: translateZ(0); + -moz-transform: translateZ(0); + -ms-transform: translateZ(0); + -o-transform: translateZ(0); + transform: translateZ(0); + -webkit-mask-image: -webkit-radial-gradient(circle, #ffffff 100%, #000000 100%); +} +.waves-button, +.waves-button:hover, +.waves-button:visited, +.waves-button-input { + white-space: nowrap; + vertical-align: middle; + cursor: pointer; + border: none; + outline: none; + color: inherit; + background-color: rgba(0, 0, 0, 0); + font-size: 1em; + line-height: 1em; + text-align: center; + text-decoration: none; + z-index: 1; +} +.waves-button { + padding: 0.85em 1.1em; + border-radius: 0.2em; +} +.waves-button-input { + margin: 0; + padding: 0.85em 1.1em; +} +.waves-input-wrapper { + border-radius: 0.2em; + vertical-align: bottom; +} +.waves-input-wrapper.waves-button { + padding: 0; +} +.waves-input-wrapper .waves-button-input { + position: relative; + top: 0; + left: 0; + z-index: 1; +} +.waves-circle { + text-align: center; + width: 2.5em; + height: 2.5em; + line-height: 2.5em; + border-radius: 50%; +} +.waves-float { + -webkit-mask-image: none; + -webkit-box-shadow: 0px 1px 1.5px 1px rgba(0, 0, 0, 0.12); + box-shadow: 0px 1px 1.5px 1px rgba(0, 0, 0, 0.12); + -webkit-transition: all 300ms; + -moz-transition: all 300ms; + -o-transition: all 300ms; + transition: all 300ms; +} +.waves-float:active { + -webkit-box-shadow: 0px 8px 20px 1px rgba(0, 0, 0, 0.3); + box-shadow: 0px 8px 20px 1px rgba(0, 0, 0, 0.3); +} +.waves-block { + display: block; +} diff --git a/src/main/resources/static/module/Waves/waves.js b/src/main/resources/static/module/Waves/waves.js new file mode 100644 index 0000000..16b754b --- /dev/null +++ b/src/main/resources/static/module/Waves/waves.js @@ -0,0 +1,582 @@ +/*! + * Waves v0.7.5 + * http://fian.my.id/Waves + * + * Copyright 2014-2016 Alfiana E. Sibuea and other contributors + * Released under the MIT license + * https://github.com/fians/Waves/blob/master/LICENSE + */ + +;(function(window, factory) { + 'use strict'; + + // AMD. Register as an anonymous module. Wrap in function so we have access + // to root via `this`. + if (typeof define === 'function' && define.amd) { + define([], function() { + return factory.apply(window); + }); + } + + // Node. Does not work with strict CommonJS, but only CommonJS-like + // environments that support module.exports, like Node. + else if (typeof exports === 'object') { + module.exports = factory.call(window); + } + + // Browser globals. + else { + window.Waves = factory.call(window); + } +})(typeof global === 'object' ? global : this, function() { + 'use strict'; + + var Waves = Waves || {}; + var $$ = document.querySelectorAll.bind(document); + var toString = Object.prototype.toString; + var isTouchAvailable = 'ontouchstart' in window; + + + // Find exact position of element + function isWindow(obj) { + return obj !== null && obj === obj.window; + } + + function getWindow(elem) { + return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView; + } + + function isObject(value) { + var type = typeof value; + return type === 'function' || type === 'object' && !!value; + } + + function isDOMNode(obj) { + return isObject(obj) && obj.nodeType > 0; + } + + function getWavesElements(nodes) { + var stringRepr = toString.call(nodes); + + if (stringRepr === '[object String]') { + return $$(nodes); + } else if (isObject(nodes) && /^\[object (Array|HTMLCollection|NodeList|Object)\]$/.test(stringRepr) && nodes.hasOwnProperty('length')) { + return nodes; + } else if (isDOMNode(nodes)) { + return [nodes]; + } + + return []; + } + + function offset(elem) { + var docElem, win, + box = { top: 0, left: 0 }, + doc = elem && elem.ownerDocument; + + docElem = doc.documentElement; + + if (typeof elem.getBoundingClientRect !== typeof undefined) { + box = elem.getBoundingClientRect(); + } + win = getWindow(doc); + return { + top: box.top + win.pageYOffset - docElem.clientTop, + left: box.left + win.pageXOffset - docElem.clientLeft + }; + } + + function convertStyle(styleObj) { + var style = ''; + + for (var prop in styleObj) { + if (styleObj.hasOwnProperty(prop)) { + style += (prop + ':' + styleObj[prop] + ';'); + } + } + + return style; + } + + var Effect = { + + // Effect duration + duration: 750, + + // Effect delay (check for scroll before showing effect) + delay: 200, + + show: function(e, element, velocity) { + + // Disable right click + if (e.button === 2) { + return false; + } + + element = element || this; + + // Create ripple + var ripple = document.createElement('div'); + ripple.className = 'waves-ripple waves-rippling'; + element.appendChild(ripple); + + // Get click coordinate and element width + var pos = offset(element); + var relativeY = 0; + var relativeX = 0; + // Support for touch devices + if('touches' in e && e.touches.length) { + relativeY = (e.touches[0].pageY - pos.top); + relativeX = (e.touches[0].pageX - pos.left); + } + //Normal case + else { + relativeY = (e.pageY - pos.top); + relativeX = (e.pageX - pos.left); + } + // Support for synthetic events + relativeX = relativeX >= 0 ? relativeX : 0; + relativeY = relativeY >= 0 ? relativeY : 0; + + var scale = 'scale(' + ((element.clientWidth / 100) * 3) + ')'; + var translate = 'translate(0,0)'; + + if (velocity) { + translate = 'translate(' + (velocity.x) + 'px, ' + (velocity.y) + 'px)'; + } + + // Attach data to element + ripple.setAttribute('data-hold', Date.now()); + ripple.setAttribute('data-x', relativeX); + ripple.setAttribute('data-y', relativeY); + ripple.setAttribute('data-scale', scale); + ripple.setAttribute('data-translate', translate); + + // Set ripple position + var rippleStyle = { + top: relativeY + 'px', + left: relativeX + 'px' + }; + + ripple.classList.add('waves-notransition'); + ripple.setAttribute('style', convertStyle(rippleStyle)); + ripple.classList.remove('waves-notransition'); + + // Scale the ripple + rippleStyle['-webkit-transform'] = scale + ' ' + translate; + rippleStyle['-moz-transform'] = scale + ' ' + translate; + rippleStyle['-ms-transform'] = scale + ' ' + translate; + rippleStyle['-o-transform'] = scale + ' ' + translate; + rippleStyle.transform = scale + ' ' + translate; + rippleStyle.opacity = '1'; + + var duration = e.type === 'mousemove' ? 2500 : Effect.duration; + rippleStyle['-webkit-transition-duration'] = duration + 'ms'; + rippleStyle['-moz-transition-duration'] = duration + 'ms'; + rippleStyle['-o-transition-duration'] = duration + 'ms'; + rippleStyle['transition-duration'] = duration + 'ms'; + + ripple.setAttribute('style', convertStyle(rippleStyle)); + }, + + hide: function(e, element) { + element = element || this; + + var ripples = element.getElementsByClassName('waves-rippling'); + + for (var i = 0, len = ripples.length; i < len; i++) { + removeRipple(e, element, ripples[i]); + } + } + }; + + /** + * Collection of wrapper for HTML element that only have single tag + * like and + */ + var TagWrapper = { + + // Wrap tag so it can perform the effect + input: function(element) { + + var parent = element.parentNode; + + // If input already have parent just pass through + if (parent.tagName.toLowerCase() === 'i' && parent.classList.contains('waves-effect')) { + return; + } + + // Put element class and style to the specified parent + var wrapper = document.createElement('i'); + wrapper.className = element.className + ' waves-input-wrapper'; + element.className = 'waves-button-input'; + + // Put element as child + parent.replaceChild(wrapper, element); + wrapper.appendChild(element); + + // Apply element color and background color to wrapper + var elementStyle = window.getComputedStyle(element, null); + var color = elementStyle.color; + var backgroundColor = elementStyle.backgroundColor; + + wrapper.setAttribute('style', 'color:' + color + ';background:' + backgroundColor); + element.setAttribute('style', 'background-color:rgba(0,0,0,0);'); + + }, + + // Wrap tag so it can perform the effect + img: function(element) { + + var parent = element.parentNode; + + // If input already have parent just pass through + if (parent.tagName.toLowerCase() === 'i' && parent.classList.contains('waves-effect')) { + return; + } + + // Put element as child + var wrapper = document.createElement('i'); + parent.replaceChild(wrapper, element); + wrapper.appendChild(element); + + } + }; + + /** + * Hide the effect and remove the ripple. Must be + * a separate function to pass the JSLint... + */ + function removeRipple(e, el, ripple) { + + // Check if the ripple still exist + if (!ripple) { + return; + } + + ripple.classList.remove('waves-rippling'); + + var relativeX = ripple.getAttribute('data-x'); + var relativeY = ripple.getAttribute('data-y'); + var scale = ripple.getAttribute('data-scale'); + var translate = ripple.getAttribute('data-translate'); + + // Get delay beetween mousedown and mouse leave + var diff = Date.now() - Number(ripple.getAttribute('data-hold')); + var delay = 350 - diff; + + if (delay < 0) { + delay = 0; + } + + if (e.type === 'mousemove') { + delay = 150; + } + + // Fade out ripple after delay + var duration = e.type === 'mousemove' ? 2500 : Effect.duration; + + setTimeout(function() { + + var style = { + top: relativeY + 'px', + left: relativeX + 'px', + opacity: '0', + + // Duration + '-webkit-transition-duration': duration + 'ms', + '-moz-transition-duration': duration + 'ms', + '-o-transition-duration': duration + 'ms', + 'transition-duration': duration + 'ms', + '-webkit-transform': scale + ' ' + translate, + '-moz-transform': scale + ' ' + translate, + '-ms-transform': scale + ' ' + translate, + '-o-transform': scale + ' ' + translate, + 'transform': scale + ' ' + translate + }; + + ripple.setAttribute('style', convertStyle(style)); + + setTimeout(function() { + try { + el.removeChild(ripple); + } catch (e) { + return false; + } + }, duration); + + }, delay); + } + + + /** + * Disable mousedown event for 500ms during and after touch + */ + var TouchHandler = { + + /* uses an integer rather than bool so there's no issues with + * needing to clear timeouts if another touch event occurred + * within the 500ms. Cannot mouseup between touchstart and + * touchend, nor in the 500ms after touchend. */ + touches: 0, + + allowEvent: function(e) { + + var allow = true; + + if (/^(mousedown|mousemove)$/.test(e.type) && TouchHandler.touches) { + allow = false; + } + + return allow; + }, + registerEvent: function(e) { + var eType = e.type; + + if (eType === 'touchstart') { + + TouchHandler.touches += 1; // push + + } else if (/^(touchend|touchcancel)$/.test(eType)) { + + setTimeout(function() { + if (TouchHandler.touches) { + TouchHandler.touches -= 1; // pop after 500ms + } + }, 500); + + } + } + }; + + + /** + * Delegated click handler for .waves-effect element. + * returns null when .waves-effect element not in "click tree" + */ + function getWavesEffectElement(e) { + + if (TouchHandler.allowEvent(e) === false) { + return null; + } + + var element = null; + var target = e.target || e.srcElement; + + while (target.parentElement) { + if ( (!(target instanceof SVGElement)) && target.classList.contains('waves-effect')) { + element = target; + break; + } + target = target.parentElement; + } + + return element; + } + + /** + * Bubble the click and show effect if .waves-effect elem was found + */ + function showEffect(e) { + + // Disable effect if element has "disabled" property on it + // In some cases, the event is not triggered by the current element + // if (e.target.getAttribute('disabled') !== null) { + // return; + // } + + var element = getWavesEffectElement(e); + + if (element !== null) { + + // Make it sure the element has either disabled property, disabled attribute or 'disabled' class + if (element.disabled || element.getAttribute('disabled') || element.classList.contains('disabled')) { + return; + } + + TouchHandler.registerEvent(e); + + if (e.type === 'touchstart' && Effect.delay) { + + var hidden = false; + + var timer = setTimeout(function () { + timer = null; + Effect.show(e, element); + }, Effect.delay); + + var hideEffect = function(hideEvent) { + + // if touch hasn't moved, and effect not yet started: start effect now + if (timer) { + clearTimeout(timer); + timer = null; + Effect.show(e, element); + } + if (!hidden) { + hidden = true; + Effect.hide(hideEvent, element); + } + }; + + var touchMove = function(moveEvent) { + if (timer) { + clearTimeout(timer); + timer = null; + } + hideEffect(moveEvent); + }; + + element.addEventListener('touchmove', touchMove, false); + element.addEventListener('touchend', hideEffect, false); + element.addEventListener('touchcancel', hideEffect, false); + + } else { + + Effect.show(e, element); + + if (isTouchAvailable) { + element.addEventListener('touchend', Effect.hide, false); + element.addEventListener('touchcancel', Effect.hide, false); + } + + element.addEventListener('mouseup', Effect.hide, false); + element.addEventListener('mouseleave', Effect.hide, false); + } + } + } + + Waves.init = function(options) { + var body = document.body; + + options = options || {}; + + if ('duration' in options) { + Effect.duration = options.duration; + } + + if ('delay' in options) { + Effect.delay = options.delay; + } + + if (isTouchAvailable) { + body.addEventListener('touchstart', showEffect, false); + body.addEventListener('touchcancel', TouchHandler.registerEvent, false); + body.addEventListener('touchend', TouchHandler.registerEvent, false); + } + + body.addEventListener('mousedown', showEffect, false); + }; + + + /** + * Attach Waves to dynamically loaded inputs, or add .waves-effect and other + * waves classes to a set of elements. Set drag to true if the ripple mouseover + * or skimming effect should be applied to the elements. + */ + Waves.attach = function(elements, classes) { + + elements = getWavesElements(elements); + + if (toString.call(classes) === '[object Array]') { + classes = classes.join(' '); + } + + classes = classes ? ' ' + classes : ''; + + var element, tagName; + + for (var i = 0, len = elements.length; i < len; i++) { + + element = elements[i]; + tagName = element.tagName.toLowerCase(); + + if (['input', 'img'].indexOf(tagName) !== -1) { + TagWrapper[tagName](element); + element = element.parentElement; + } + + if (element.className.indexOf('waves-effect') === -1) { + element.className += ' waves-effect' + classes; + } + } + }; + + + /** + * Cause a ripple to appear in an element via code. + */ + Waves.ripple = function(elements, options) { + elements = getWavesElements(elements); + var elementsLen = elements.length; + + options = options || {}; + options.wait = options.wait || 0; + options.position = options.position || null; // default = centre of element + + + if (elementsLen) { + var element, pos, off, centre = {}, i = 0; + var mousedown = { + type: 'mousedown', + button: 1 + }; + var hideRipple = function(mouseup, element) { + return function() { + Effect.hide(mouseup, element); + }; + }; + + for (; i < elementsLen; i++) { + element = elements[i]; + pos = options.position || { + x: element.clientWidth / 2, + y: element.clientHeight / 2 + }; + + off = offset(element); + centre.x = off.left + pos.x; + centre.y = off.top + pos.y; + + mousedown.pageX = centre.x; + mousedown.pageY = centre.y; + + Effect.show(mousedown, element); + + if (options.wait >= 0 && options.wait !== null) { + var mouseup = { + type: 'mouseup', + button: 1 + }; + + setTimeout(hideRipple(mouseup, element), options.wait); + } + } + } + }; + + /** + * Remove all ripples from an element. + */ + Waves.calm = function(elements) { + elements = getWavesElements(elements); + var mouseup = { + type: 'mouseup', + button: 1 + }; + + for (var i = 0, len = elements.length; i < len; i++) { + Effect.hide(mouseup, elements[i]); + } + }; + + /** + * Deprecated API fallback + */ + Waves.displayEffect = function(options) { + console.error('Waves.displayEffect() has been deprecated and will be removed in future version. Please use Waves.init() to initialize Waves effect'); + Waves.init(options); + }; + + return Waves; +}); diff --git a/src/main/resources/static/module/Waves/waves.min.css b/src/main/resources/static/module/Waves/waves.min.css new file mode 100644 index 0000000..b06e752 --- /dev/null +++ b/src/main/resources/static/module/Waves/waves.min.css @@ -0,0 +1,8 @@ +/*! + * Waves v0.7.5 + * http://fian.my.id/Waves + * + * Copyright 2014-2016 Alfiana E. Sibuea and other contributors + * Released under the MIT license + * https://github.com/fians/Waves/blob/master/LICENSE + */.waves-effect{position:relative;cursor:pointer;display:inline-block;overflow:hidden;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}.waves-effect .waves-ripple{position:absolute;border-radius:50%;width:100px;height:100px;margin-top:-50px;margin-left:-50px;opacity:0;background:rgba(0,0,0,.2);background:-webkit-radial-gradient(rgba(0,0,0,.2) 0,rgba(0,0,0,.3) 40%,rgba(0,0,0,.4) 50%,rgba(0,0,0,.5) 60%,rgba(255,255,255,0) 70%);background:-o-radial-gradient(rgba(0,0,0,.2) 0,rgba(0,0,0,.3) 40%,rgba(0,0,0,.4) 50%,rgba(0,0,0,.5) 60%,rgba(255,255,255,0) 70%);background:-moz-radial-gradient(rgba(0,0,0,.2) 0,rgba(0,0,0,.3) 40%,rgba(0,0,0,.4) 50%,rgba(0,0,0,.5) 60%,rgba(255,255,255,0) 70%);background:radial-gradient(rgba(0,0,0,.2) 0,rgba(0,0,0,.3) 40%,rgba(0,0,0,.4) 50%,rgba(0,0,0,.5) 60%,rgba(255,255,255,0) 70%);-webkit-transition:all .5s ease-out;-moz-transition:all .5s ease-out;-o-transition:all .5s ease-out;transition:all .5s ease-out;-webkit-transition-property:-webkit-transform,opacity;-moz-transition-property:-moz-transform,opacity;-o-transition-property:-o-transform,opacity;transition-property:transform,opacity;-webkit-transform:scale(0) translate(0,0);-moz-transform:scale(0) translate(0,0);-ms-transform:scale(0) translate(0,0);-o-transform:scale(0) translate(0,0);transform:scale(0) translate(0,0);pointer-events:none}.waves-effect.waves-light .waves-ripple{background:rgba(255,255,255,.4);background:-webkit-radial-gradient(rgba(255,255,255,.2) 0,rgba(255,255,255,.3) 40%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.5) 60%,rgba(255,255,255,0) 70%);background:-o-radial-gradient(rgba(255,255,255,.2) 0,rgba(255,255,255,.3) 40%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.5) 60%,rgba(255,255,255,0) 70%);background:-moz-radial-gradient(rgba(255,255,255,.2) 0,rgba(255,255,255,.3) 40%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.5) 60%,rgba(255,255,255,0) 70%);background:radial-gradient(rgba(255,255,255,.2) 0,rgba(255,255,255,.3) 40%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.5) 60%,rgba(255,255,255,0) 70%)}.waves-effect.waves-classic .waves-ripple{background:rgba(0,0,0,.2)}.waves-effect.waves-classic.waves-light .waves-ripple{background:rgba(255,255,255,.4)}.waves-notransition{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.waves-button,.waves-circle{-webkit-transform:translateZ(0);-moz-transform:translateZ(0);-ms-transform:translateZ(0);-o-transform:translateZ(0);transform:translateZ(0);-webkit-mask-image:-webkit-radial-gradient(circle,#fff 100%,#000 100%)}.waves-button,.waves-button:hover,.waves-button:visited,.waves-button-input{white-space:nowrap;vertical-align:middle;cursor:pointer;border:none;outline:0;color:inherit;background-color:transparent;font-size:1em;line-height:1em;text-align:center;text-decoration:none;z-index:1}.waves-button{padding:.85em 1.1em;border-radius:.2em}.waves-button-input{margin:0;padding:.85em 1.1em}.waves-input-wrapper{border-radius:.2em;vertical-align:bottom}.waves-input-wrapper.waves-button{padding:0}.waves-input-wrapper .waves-button-input{position:relative;top:0;left:0;z-index:1}.waves-circle{text-align:center;width:2.5em;height:2.5em;line-height:2.5em;border-radius:50%}.waves-float{-webkit-mask-image:none;-webkit-box-shadow:0 1px 1.5px 1px rgba(0,0,0,.12);box-shadow:0 1px 1.5px 1px rgba(0,0,0,.12);-webkit-transition:all 300ms;-moz-transition:all 300ms;-o-transition:all 300ms;transition:all 300ms}.waves-float:active{-webkit-box-shadow:0 8px 20px 1px rgba(0,0,0,.3);box-shadow:0 8px 20px 1px rgba(0,0,0,.3)}.waves-block{display:block} \ No newline at end of file diff --git a/src/main/resources/static/module/Waves/waves.min.js b/src/main/resources/static/module/Waves/waves.min.js new file mode 100644 index 0000000..6d4f34f --- /dev/null +++ b/src/main/resources/static/module/Waves/waves.min.js @@ -0,0 +1,10 @@ +/*! + * Waves v0.7.5 + * http://fian.my.id/Waves + * + * Copyright 2014-2016 Alfiana E. Sibuea and other contributors + * Released under the MIT license + * https://github.com/fians/Waves/blob/master/LICENSE + */ +!function(a,b){"use strict";"function"==typeof define&&define.amd?define([],function(){return b.apply(a)}):"object"==typeof exports?module.exports=b.call(a):a.Waves=b.call(a)}("object"==typeof global?global:this,function(){"use strict";function a(a){return null!==a&&a===a.window}function b(b){return a(b)?b:9===b.nodeType&&b.defaultView}function c(a){var b=typeof a;return"function"===b||"object"===b&&!!a}function d(a){return c(a)&&a.nodeType>0}function e(a){var b=m.call(a);return"[object String]"===b?l(a):c(a)&&/^\[object (Array|HTMLCollection|NodeList|Object)\]$/.test(b)&&a.hasOwnProperty("length")?a:d(a)?[a]:[]}function f(a){var c,d,e={top:0,left:0},f=a&&a.ownerDocument;return c=f.documentElement,"undefined"!=typeof a.getBoundingClientRect&&(e=a.getBoundingClientRect()),d=b(f),{top:e.top+d.pageYOffset-c.clientTop,left:e.left+d.pageXOffset-c.clientLeft}}function g(a){var b="";for(var c in a)a.hasOwnProperty(c)&&(b+=c+":"+a[c]+";");return b}function h(a,b,c){if(c){c.classList.remove("waves-rippling");var d=c.getAttribute("data-x"),e=c.getAttribute("data-y"),f=c.getAttribute("data-scale"),h=c.getAttribute("data-translate"),i=Date.now()-Number(c.getAttribute("data-hold")),j=350-i;0>j&&(j=0),"mousemove"===a.type&&(j=150);var k="mousemove"===a.type?2500:o.duration;setTimeout(function(){var a={top:e+"px",left:d+"px",opacity:"0","-webkit-transition-duration":k+"ms","-moz-transition-duration":k+"ms","-o-transition-duration":k+"ms","transition-duration":k+"ms","-webkit-transform":f+" "+h,"-moz-transform":f+" "+h,"-ms-transform":f+" "+h,"-o-transform":f+" "+h,transform:f+" "+h};c.setAttribute("style",g(a)),setTimeout(function(){try{b.removeChild(c)}catch(a){return!1}},k)},j)}}function i(a){if(q.allowEvent(a)===!1)return null;for(var b=null,c=a.target||a.srcElement;c.parentElement;){if(!(c instanceof SVGElement)&&c.classList.contains("waves-effect")){b=c;break}c=c.parentElement}return b}function j(a){var b=i(a);if(null!==b){if(b.disabled||b.getAttribute("disabled")||b.classList.contains("disabled"))return;if(q.registerEvent(a),"touchstart"===a.type&&o.delay){var c=!1,d=setTimeout(function(){d=null,o.show(a,b)},o.delay),e=function(e){d&&(clearTimeout(d),d=null,o.show(a,b)),c||(c=!0,o.hide(e,b))},f=function(a){d&&(clearTimeout(d),d=null),e(a)};b.addEventListener("touchmove",f,!1),b.addEventListener("touchend",e,!1),b.addEventListener("touchcancel",e,!1)}else o.show(a,b),n&&(b.addEventListener("touchend",o.hide,!1),b.addEventListener("touchcancel",o.hide,!1)),b.addEventListener("mouseup",o.hide,!1),b.addEventListener("mouseleave",o.hide,!1)}}var k=k||{},l=document.querySelectorAll.bind(document),m=Object.prototype.toString,n="ontouchstart"in window,o={duration:750,delay:200,show:function(a,b,c){if(2===a.button)return!1;b=b||this;var d=document.createElement("div");d.className="waves-ripple waves-rippling",b.appendChild(d);var e=f(b),h=0,i=0;"touches"in a&&a.touches.length?(h=a.touches[0].pageY-e.top,i=a.touches[0].pageX-e.left):(h=a.pageY-e.top,i=a.pageX-e.left),i=i>=0?i:0,h=h>=0?h:0;var j="scale("+b.clientWidth/100*3+")",k="translate(0,0)";c&&(k="translate("+c.x+"px, "+c.y+"px)"),d.setAttribute("data-hold",Date.now()),d.setAttribute("data-x",i),d.setAttribute("data-y",h),d.setAttribute("data-scale",j),d.setAttribute("data-translate",k);var l={top:h+"px",left:i+"px"};d.classList.add("waves-notransition"),d.setAttribute("style",g(l)),d.classList.remove("waves-notransition"),l["-webkit-transform"]=j+" "+k,l["-moz-transform"]=j+" "+k,l["-ms-transform"]=j+" "+k,l["-o-transform"]=j+" "+k,l.transform=j+" "+k,l.opacity="1";var m="mousemove"===a.type?2500:o.duration;l["-webkit-transition-duration"]=m+"ms",l["-moz-transition-duration"]=m+"ms",l["-o-transition-duration"]=m+"ms",l["transition-duration"]=m+"ms",d.setAttribute("style",g(l))},hide:function(a,b){b=b||this;for(var c=b.getElementsByClassName("waves-rippling"),d=0,e=c.length;e>d;d++)h(a,b,c[d])}},p={input:function(a){var b=a.parentNode;if("i"!==b.tagName.toLowerCase()||!b.classList.contains("waves-effect")){var c=document.createElement("i");c.className=a.className+" waves-input-wrapper",a.className="waves-button-input",b.replaceChild(c,a),c.appendChild(a);var d=window.getComputedStyle(a,null),e=d.color,f=d.backgroundColor;c.setAttribute("style","color:"+e+";background:"+f),a.setAttribute("style","background-color:rgba(0,0,0,0);")}},img:function(a){var b=a.parentNode;if("i"!==b.tagName.toLowerCase()||!b.classList.contains("waves-effect")){var c=document.createElement("i");b.replaceChild(c,a),c.appendChild(a)}}},q={touches:0,allowEvent:function(a){var b=!0;return/^(mousedown|mousemove)$/.test(a.type)&&q.touches&&(b=!1),b},registerEvent:function(a){var b=a.type;"touchstart"===b?q.touches+=1:/^(touchend|touchcancel)$/.test(b)&&setTimeout(function(){q.touches&&(q.touches-=1)},500)}};return k.init=function(a){var b=document.body;a=a||{},"duration"in a&&(o.duration=a.duration),"delay"in a&&(o.delay=a.delay),n&&(b.addEventListener("touchstart",j,!1),b.addEventListener("touchcancel",q.registerEvent,!1),b.addEventListener("touchend",q.registerEvent,!1)),b.addEventListener("mousedown",j,!1)},k.attach=function(a,b){a=e(a),"[object Array]"===m.call(b)&&(b=b.join(" ")),b=b?" "+b:"";for(var c,d,f=0,g=a.length;g>f;f++)c=a[f],d=c.tagName.toLowerCase(),-1!==["input","img"].indexOf(d)&&(p[d](c),c=c.parentElement),-1===c.className.indexOf("waves-effect")&&(c.className+=" waves-effect"+b)},k.ripple=function(a,b){a=e(a);var c=a.length;if(b=b||{},b.wait=b.wait||0,b.position=b.position||null,c)for(var d,g,h,i={},j=0,k={type:"mousedown",button:1},l=function(a,b){return function(){o.hide(a,b)}};c>j;j++)if(d=a[j],g=b.position||{x:d.clientWidth/2,y:d.clientHeight/2},h=f(d),i.x=h.left+g.x,i.y=h.top+g.y,k.pageX=i.x,k.pageY=i.y,o.show(k,d),b.wait>=0&&null!==b.wait){var m={type:"mouseup",button:1};setTimeout(l(m,d),b.wait)}},k.calm=function(a){a=e(a);for(var b={type:"mouseup",button:1},c=0,d=a.length;d>c;c++)o.hide(b,a[c])},k.displayEffect=function(a){k.init(a)},k}); +//# sourceMappingURL=waves.min.js.map \ No newline at end of file diff --git a/src/main/resources/static/module/Waves/waves.min.js.map b/src/main/resources/static/module/Waves/waves.min.js.map new file mode 100644 index 0000000..3fec14d --- /dev/null +++ b/src/main/resources/static/module/Waves/waves.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/js/waves.js"],"names":["window","factory","define","amd","apply","exports","module","call","Waves","global","this","isWindow","obj","getWindow","elem","nodeType","defaultView","isObject","value","type","isDOMNode","getWavesElements","nodes","stringRepr","toString","$$","test","hasOwnProperty","offset","docElem","win","box","top","left","doc","ownerDocument","documentElement","getBoundingClientRect","pageYOffset","clientTop","pageXOffset","clientLeft","convertStyle","styleObj","style","prop","removeRipple","e","el","ripple","classList","remove","relativeX","getAttribute","relativeY","scale","translate","diff","Date","now","Number","delay","duration","Effect","setTimeout","opacity","-webkit-transition-duration","-moz-transition-duration","-o-transition-duration","transition-duration","-webkit-transform","-moz-transform","-ms-transform","-o-transform","transform","setAttribute","removeChild","getWavesEffectElement","TouchHandler","allowEvent","element","target","srcElement","parentElement","SVGElement","contains","showEffect","disabled","registerEvent","hidden","timer","show","hideEffect","hideEvent","clearTimeout","hide","touchMove","moveEvent","addEventListener","isTouchAvailable","document","querySelectorAll","bind","Object","prototype","velocity","button","createElement","className","appendChild","pos","touches","length","pageY","pageX","clientWidth","rippleStyle","add","ripples","getElementsByClassName","i","len","TagWrapper","input","parent","parentNode","tagName","toLowerCase","wrapper","replaceChild","elementStyle","getComputedStyle","color","backgroundColor","img","allow","eType","init","options","body","attach","elements","classes","join","indexOf","elementsLen","wait","position","off","centre","mousedown","hideRipple","mouseup","x","y","clientHeight","calm","displayEffect"],"mappings":"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","file":"waves.min.js"} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-chips/angular-chips.js b/src/main/resources/static/module/angular-chips/angular-chips.js new file mode 100644 index 0000000..0b3847f --- /dev/null +++ b/src/main/resources/static/module/angular-chips/angular-chips.js @@ -0,0 +1,469 @@ +(function() { + Chips.$inject = ["$compile", "$timeout", "DomUtil"]; + ChipsController.$inject = ["$scope", "$element", "DomUtil"]; + angular.module('angular.chips', []) + .directive('chips', Chips) + .controller('chipsController', ChipsController); + + function isPromiseLike(obj) { + return obj && angular.isFunction(obj.then); + } + + /* + * update values to ngModel reference + */ + function ngModel(modelCtrl) { + return { + add: function(val) { + var modelCopy = angular.copy(modelCtrl.$modelValue) || []; + modelCopy.push(val) + modelCtrl.$setViewValue(modelCopy); + }, + delete: function(index) { + var modelCopy = angular.copy(modelCtrl.$modelValue); + modelCopy.splice(index, 1); + modelCtrl.$setViewValue(modelCopy); + }, + deleteByValue: function(val) { + var index, resultIndex; + for (index = 0; index < modelCtrl.$modelValue.length; index++) { + if (angular.equals(modelCtrl.$modelValue[index], val)) { + resultIndex = index; + break; + } + + } + if (resultIndex !== undefined) + this.delete(resultIndex) + } + } + } + + function DeferChip(data, promise) { + var self = this; + this.type = 'defer'; + this.defer = data; + this.isLoading = false; + this.isFailed = false; + + if (promise) { + self.isLoading = true; + promise.then(function(data) { + self.defer = data; + self.isLoading = false; + }, function(data) { + self.defer = data; + self.isLoading = false; + self.isFailed = true; + }); + } + } + + /* + * get function param key + * example: 'render(data)' data is the key here + * getParamKey('render(data)') will return data + */ + function getParamKey(funStr) { + if (funStr === undefined) + return; + var openParenthesisIndex, closeParenthesisIndex; + openParenthesisIndex = funStr.indexOf('(') + 1; + closeParenthesisIndex = funStr.indexOf(')'); + return funStr.substr(openParenthesisIndex, closeParenthesisIndex - openParenthesisIndex); + } + /*@ngInject*/ + function Chips($compile, $timeout, DomUtil) { + /*@ngInject*/ + linkFun.$inject = ["scope", "iElement", "iAttrs", "ngModelCtrl", "transcludefn"]; + function linkFun(scope, iElement, iAttrs, ngModelCtrl, transcludefn) { + if ((error = validation(iElement)) !== '') { + throw error; + } + + var model = ngModel(ngModelCtrl); + var isDeferFlow = iAttrs.hasOwnProperty('defer'); + var functionParam = getParamKey(iAttrs.render); + + /* + * @scope.chips.addChip should be called by chipControl directive or custom XXXcontrol directive developed by end user + * @scope.chips.deleteChip will be called by removeChip directive + * + */ + + /* + * ngModel values are copies here + */ + scope.chips.list; + + scope.chips.addChip = function(data) { + var updatedData, paramObj; + + if (scope.render !== undefined && functionParam !== '') { + paramObj = {}; + paramObj[functionParam] = data; + updatedData = scope.render(paramObj); + } else { updatedData = data } + + if (!updatedData) { + return false; + } + + if (isPromiseLike(updatedData)) { + updatedData.then(function(response) { + model.add(response); + }); + scope.chips.list.push(new DeferChip(data, updatedData)); + scope.$apply(); + } else { + update(updatedData); + } + + function update(data) { + scope.chips.list.push(data); + model.add(data); + } + + return true; + }; + + scope.chips.deleteChip = function(index) { + var deletedChip = scope.chips.list.splice(index, 1)[0]; + if (deletedChip.isFailed) { + scope.$apply(); + return; + } + + deletedChip instanceof DeferChip ? model.deleteByValue(deletedChip.defer) : model.delete(index); + } + + /* + * ngModel values are copied when it's updated outside + */ + ngModelCtrl.$render = function() { + if (isDeferFlow && ngModelCtrl.$modelValue) { + var index, list = []; + for (index = 0; index < ngModelCtrl.$modelValue.length; index++) { + // list.push(ngModelCtrl.$modelValue[index]); + list.push(new DeferChip(ngModelCtrl.$modelValue[index])) + } + scope.chips.list = list; + } else { + scope.chips.list = angular.copy(ngModelCtrl.$modelValue) || []; + } + + } + + var chipNavigate = null; + /* + * @index selected chip index + * @return function, which will return the chip index based on left or right arrow pressed + */ + function chipNavigator(index) { + return function(direction) { + direction === 37 ? index-- : index++; + index = index < 0 ? scope.chips.list.length - 1 : index > scope.chips.list.length - 1 ? 0 : index; + return index; + } + } + + /*Extract the chip-tmpl and compile inside the chips directive scope*/ + var rootDiv = angular.element('
'); + var tmplStr = iElement.html(); + tmplStr = tmplStr.substr(tmplStr.indexOf('')-('').length); + iElement.find('chip-tmpl').remove(); + var tmpl = angular.element(tmplStr); + var chipTextNode, chipBindedData, chipBindedDataSuffix; + tmpl.attr('ng-repeat', 'chip in chips.list track by $index'); + tmpl.attr('ng-class', '{\'chip-failed\':chip.isFailed}') + tmpl.attr('tabindex', '-1') + tmpl.attr('index', '{{$index+1}}') + rootDiv.append(tmpl); + var node = $compile(rootDiv)(scope); + iElement.prepend(node); + + + /*clicking on chips element should set the focus on INPUT*/ + iElement.on('click', function(event) { + if (event.target.nodeName === 'CHIPS') + iElement.find('input')[0].focus(); + }); + /*on every focus we need to nullify the chipNavigate*/ + iElement.find('input').on('focus', function() { + chipNavigate = null; + }); + /*this method will handle 'delete or Backspace' and left, right key press*/ + scope.chips.handleKeyDown = function(event) { + if (event.target.nodeName !== 'INPUT' && event.target.nodeName !== 'CHIP-TMPL' || (iElement.find('chip-tmpl').length === 0 && event.target.value === '')) + return; + + var chipTmpls; + + function focusOnChip() { + var index = parseInt(document.activeElement.getAttribute('index')) || (chipTmpls = iElement.find('chip-tmpl')).length; + chipTmpls = iElement.find('chip-tmpl'); + chipTmpls[index - 1].focus(); + chipNavigate = chipNavigator(index-1); + if(event.target.nodeName !== 'INPUT') + chipTmpls[chipNavigate(event.keyCode)].focus(); + } + + if (event.keyCode === 8) { + if (event.target.nodeName === 'INPUT' && event.target.value === '') { + focusOnChip(); + event.preventDefault(); + } else if (event.target.nodeName === 'CHIP-TMPL') { + /* + * This block will be called during chip deletion using delete or Backspace key + * Below code will set the focus of the next available chip + */ + var chipTemplates = iElement.find('chip-tmpl'); + if (chipTemplates.length > 0 && parseInt(event.target.getAttribute('index')) - 1 === chipTemplates.length) + iElement.find('chip-tmpl')[chipNavigate(37)].focus(); + } + + } else if (event.keyCode === 37 || event.keyCode === 39) { + chipNavigate === null ? focusOnChip() : iElement.find('chip-tmpl')[chipNavigate(event.keyCode)].focus(); + } + }; + + iElement.on('keydown', scope.chips.handleKeyDown); + + DomUtil(iElement).addClass('chip-out-focus'); + } + + return { + restrict: 'E', + scope: { + /* + * optional callback, this will be called before rendering the data, + * user can modify the data before it's rendered + */ + render: '&?' + }, + transclude: true, + require: 'ngModel', + link: linkFun, + controller: 'chipsController', + controllerAs: 'chips', + template: '
' + } + + + }; + /* tag is mandatory added validation to confirm that*/ + function validation(element) { + return element.find('chip-tmpl').length === 0 ? 'should have chip-tmpl' : element.find('chip-tmpl').length > 1 ? 'should have only one chip-tmpl' : ''; + } + /*@ngInject*/ + function ChipsController($scope, $element, DomUtil) { + /*toggling input controller focus*/ + this.setFocus = function(flag) { + if (flag) { + DomUtil($element).removeClass('chip-out-focus').addClass('chip-in-focus'); + } else { + DomUtil($element).removeClass('chip-in-focus').addClass('chip-out-focus'); + } + } + this.removeChip = function(data, index) { + this.deleteChip(index); + } + } +})(); + +(function() { + angular.module('angular.chips') + .directive('chipTmpl', ChipTmpl); + + function ChipTmpl() { + return { + restrict: 'E', + transclude: true, + link: function(scope, iElement, iAttrs, contrl, transcludefn) { + transcludefn(scope, function(clonedTranscludedContent) { + iElement.append(clonedTranscludedContent); + }); + iElement.on('keydown', function(event) { + if (event.keyCode === 8) { + scope.$broadcast('chip:delete'); + event.preventDefault(); + } + }); + } + } + } +})(); + +(function() { + angular.module('angular.chips') + .directive('removeChip', RemoveChip); + /* + * Will remove the chip + * remove-chip="callback(chip)"> call back will be triggered before remove + * Call back method should return true to remove or false for nothing + */ + function RemoveChip() { + return { + restrict: 'A', + require: '^?chips', + link: function(scope, iElement, iAttrs, chipsCtrl) { + + function getCallBack(scope, prop) { + var target; + if (prop.search('\\(') > 0) { + prop = prop.substr(0, prop.search('\\(')); + } + if (prop !== undefined) { + if (prop.split('.').length > 1) { + var levels = prop.split('.'); + target = scope; + for (var index = 0; index < levels.length; index++) { + target = target[levels[index]]; + } + } else { + target = scope[prop]; + } + } + return target; + }; + + /* + * traverse scope hierarchy and find the scope + */ + function findScope(scope, prop) { + var funStr = prop.indexOf('.') !== -1 ? prop.split('.')[0] : prop.split('(')[0]; + if (!scope.hasOwnProperty(funStr)) { + return findScope(scope.$parent, prop) + } + return scope; + }; + + function deleteChip() { + // don't delete the chip which is loading + if (typeof scope.chip !== 'string' && scope.chip.isLoading) + return; + var callBack, deleteIt = true; + if (iAttrs.hasOwnProperty('removeChip') && iAttrs.removeChip !== '') { + callBack = getCallBack(findScope(scope, iAttrs.removeChip), iAttrs.removeChip); + deleteIt = callBack(scope.chip); + } + if (deleteIt) + chipsCtrl.removeChip(scope.chip, scope.$index); + }; + + iElement.on('click', function() { + deleteChip(); + }); + + scope.$on('chip:delete', function() { + deleteChip(); + }); + + } + } + } +})(); + +(function() { + angular.module('angular.chips') + .factory('DomUtil', function() { + return DomUtil; + }); + /*Dom related functionality*/ + function DomUtil(element) { + /* + * addclass will append class to the given element + * ng-class will do the same functionality, in our case + * we don't have access to scope so we are using this util methods + */ + var utilObj = {}; + + utilObj.addClass = function(className) { + utilObj.removeClass(element, className); + element.attr('class', element.attr('class') + ' ' + className); + return utilObj; + }; + + utilObj.removeClass = function(className) { + var classes = element.attr('class').split(' '); + var classIndex = classes.indexOf(className); + if (classIndex !== -1) { + classes.splice(classIndex, 1); + } + element.attr('class', classes.join(' ')); + return utilObj; + }; + + return utilObj; + } +})(); + +(function() { + ChipControlLinkFun.$inject = ["scope", "iElement", "iAttrs", "chipsCtrl"]; + angular.module('angular.chips') + .directive('chipControl', ChipControl); + + /* + * It's for normal input element + * It send the value to chips directive when press the enter button + */ + function ChipControl() { + return { + restrict: 'A', + require: '^chips', + link: ChipControlLinkFun, + } + }; + /*@ngInject*/ + function ChipControlLinkFun(scope, iElement, iAttrs, chipsCtrl) { + iElement.on('keypress', function(event) { + if (event.keyCode === 13) { + if (event.target.value !== '' && chipsCtrl.addChip(event.target.value)) { + event.target.value = ""; + } + event.preventDefault(); + } + }); + + iElement.on('focus', function() { + chipsCtrl.setFocus(true); + }); + iElement.on('blur', function() { + chipsCtrl.setFocus(false); + }); + }; +})(); + +(function() { + angular.module('angular.chips') + .directive('ngModelControl', NGModelControl); + + /* + * It's for input element which uses ng-model directive + * example: bootstrap typeahead component + */ + function NGModelControl() { + return { + restrict: 'A', + require: ['ngModel', '^chips'], + link: function(scope, iElement, iAttrs, controller) { + var ngModelCtrl = controller[0], + chipsCtrl = controller[1]; + ngModelCtrl.$render = function(event) { + if (!ngModelCtrl.$modelValue) + return; + if (chipsCtrl.addChip(ngModelCtrl.$modelValue)) { + iElement.val(''); + } + } + + iElement.on('focus', function() { + chipsCtrl.setFocus(true); + }); + iElement.on('blur', function() { + chipsCtrl.setFocus(false); + }); + } + } + } +})(); diff --git a/src/main/resources/static/module/angular-chips/angular-chips.min.js b/src/main/resources/static/module/angular-chips/angular-chips.min.js new file mode 100644 index 0000000..0d7fdb1 --- /dev/null +++ b/src/main/resources/static/module/angular-chips/angular-chips.min.js @@ -0,0 +1 @@ +!function(){function e(e){return e&&angular.isFunction(e.then)}function n(e){return{add:function(n){var t=angular.copy(e.$modelValue)||[];t.push(n),e.$setViewValue(t)},"delete":function(n){var t=angular.copy(e.$modelValue);t.splice(n,1),e.$setViewValue(t)},deleteByValue:function(n){var t,i;for(t=0;tl.chips.list.length-1?0:e}}if(""!==(error=o(a)))throw error;var f=n(s),h=u.hasOwnProperty("defer"),m=i(u.render);l.chips.list,l.chips.addChip=function(n){function i(e){l.chips.list.push(e),f.add(e)}var r,o;return void 0!==l.render&&""!==m?(o={},o[m]=n,r=l.render(o)):r=n,!!r&&(e(r)?(r.then(function(e){f.add(e)}),l.chips.list.push(new t(n,r)),l.$apply()):i(r),!0)},l.chips.deleteChip=function(e){var n=l.chips.list.splice(e,1)[0];return n.isFailed?void l.$apply():void(n instanceof t?f.deleteByValue(n.defer):f["delete"](e))},s.$render=function(){if(h&&s.$modelValue){var e,n=[];for(e=0;e"),C=a.html();C=C.substr(C.indexOf("")-"".length),a.find("chip-tmpl").remove();var $=angular.element(C);$.attr("ng-repeat","chip in chips.list track by $index"),$.attr("ng-class","{'chip-failed':chip.isFailed}"),$.attr("tabindex","-1"),$.attr("index","{{$index+1}}"),g.append($);var y=r(g)(l);a.prepend(y),a.on("click",function(e){"CHIPS"===e.target.nodeName&&a.find("input")[0].focus()}),a.find("input").on("focus",function(){v=null}),l.chips.handleKeyDown=function(e){function n(){var n=parseInt(document.activeElement.getAttribute("index"))||(t=a.find("chip-tmpl")).length;t=a.find("chip-tmpl"),t[n-1].focus(),v=p(n-1),"INPUT"!==e.target.nodeName&&t[v(e.keyCode)].focus()}if(!("INPUT"!==e.target.nodeName&&"CHIP-TMPL"!==e.target.nodeName||0===a.find("chip-tmpl").length&&""===e.target.value)){var t;if(8===e.keyCode){if("INPUT"===e.target.nodeName&&""===e.target.value)n(),e.preventDefault();else if("CHIP-TMPL"===e.target.nodeName){var i=a.find("chip-tmpl");i.length>0&&parseInt(e.target.getAttribute("index"))-1===i.length&&a.find("chip-tmpl")[v(37)].focus()}}else 37!==e.keyCode&&39!==e.keyCode||(null===v?n():a.find("chip-tmpl")[v(e.keyCode)].focus())}},a.on("keydown",l.chips.handleKeyDown),c(a).addClass("chip-out-focus")}return a.$inject=["scope","iElement","iAttrs","ngModelCtrl","transcludefn"],{restrict:"E",scope:{render:"&?"},transclude:!0,require:"ngModel",link:a,controller:"chipsController",controllerAs:"chips",template:"
"}}function o(e){return 0===e.find("chip-tmpl").length?"should have chip-tmpl":e.find("chip-tmpl").length>1?"should have only one chip-tmpl":""}function l(e,n,t){this.setFocus=function(e){e?t(n).removeClass("chip-out-focus").addClass("chip-in-focus"):t(n).removeClass("chip-in-focus").addClass("chip-out-focus")},this.removeChip=function(e,n){this.deleteChip(n)}}r.$inject=["$compile","$timeout","DomUtil"],l.$inject=["$scope","$element","DomUtil"],angular.module("angular.chips",[]).directive("chips",r).controller("chipsController",l)}(),function(){function e(){return{restrict:"E",transclude:!0,link:function(e,n,t,i,r){r(e,function(e){n.append(e)}),n.on("keydown",function(n){8===n.keyCode&&(e.$broadcast("chip:delete"),n.preventDefault())})}}}angular.module("angular.chips").directive("chipTmpl",e)}(),function(){function e(){return{restrict:"A",require:"^?chips",link:function(e,n,t,i){function r(e,n){var t;if(n.search("\\(")>0&&(n=n.substr(0,n.search("\\("))),void 0!==n)if(n.split(".").length>1){var i=n.split(".");t=e;for(var r=0;r div { + display: inline; } + chips > div > input { + height: 100%; + border: none; + font-size: 14px; } + chips > div > input:focus { + outline: none; } + +.chip-out-focus { + border-bottom: 1px solid #e0e0e0; } + +.chip-in-focus { + border-bottom: 1px solid #106cc8; } diff --git a/src/main/resources/static/module/angular-chosen/.bower.json b/src/main/resources/static/module/angular-chosen/.bower.json new file mode 100644 index 0000000..077058c --- /dev/null +++ b/src/main/resources/static/module/angular-chosen/.bower.json @@ -0,0 +1,24 @@ +{ + "name": "angular-chosen-localytics", + "version": "1.0.7", + "main": "chosen.js", + "ignore": [ + "src", + "example" + ], + "dependencies": { + "chosen": "https://github.com/harvesthq/chosen/releases/download/v1.1.0/chosen_v1.1.0.zip", + "angular": ">=1.2.0" + }, + "homepage": "https://github.com/localytics/angular-chosen", + "_release": "1.0.7", + "_resolution": { + "type": "version", + "tag": "1.0.7", + "commit": "807894aa8a4673dc38eceae19476306610ac8684" + }, + "_source": "git://github.com/localytics/angular-chosen.git", + "_target": "~1.0.7", + "_originalSource": "angular-chosen-localytics", + "_direct": true +} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-chosen/angular-chosen.js b/src/main/resources/static/module/angular-chosen/angular-chosen.js new file mode 100644 index 0000000..bd8424a --- /dev/null +++ b/src/main/resources/static/module/angular-chosen/angular-chosen.js @@ -0,0 +1,164 @@ +/** + * angular-chosen-localytics - Angular Chosen directive is an AngularJS Directive that brings the Chosen jQuery in a Angular way + * @version v1.9.2 + * @link http://github.com/leocaseiro/angular-chosen + * @license MIT + */ +(function() { + var chosenModule, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + + angular.module('localytics.directives', []); + + chosenModule = angular.module('localytics.directives'); + + chosenModule.provider('chosen', function() { + var options; + options = {}; + return { + setOption: function(newOpts) { + angular.extend(options, newOpts); + }, + $get: function() { + return options; + } + }; + }); + + chosenModule.directive('chosen', [ + 'chosen', '$timeout', '$parse', function(config, $timeout, $parse) { + var CHOSEN_OPTION_WHITELIST, NG_OPTIONS_REGEXP, isEmpty, snakeCase; + NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/; + CHOSEN_OPTION_WHITELIST = ['persistentCreateOption', 'createOptionText', 'createOption', 'skipNoResults', 'noResultsText', 'allowSingleDeselect', 'disableSearchThreshold', 'disableSearch', 'enableSplitWordSearch', 'inheritSelectClasses', 'maxSelectedOptions', 'placeholderTextMultiple', 'placeholderTextSingle', 'searchContains', 'singleBackstrokeDelete', 'displayDisabledOptions', 'displaySelectedOptions', 'width', 'includeGroupLabelInSelected', 'maxShownResults']; + snakeCase = function(input) { + return input.replace(/[A-Z]/g, function($1) { + return "_" + ($1.toLowerCase()); + }); + }; + isEmpty = function(value) { + var key; + if (angular.isArray(value)) { + return value.length === 0; + } else if (angular.isObject(value)) { + for (key in value) { + if (value.hasOwnProperty(key)) { + return false; + } + } + } + return true; + }; + return { + restrict: 'A', + require: ['select', '?ngModel'], + priority: 1, + link: function(scope, element, attr, ctrls) { + var $render, chosen, directiveOptions, disableIfEmpty, empty, initIfNot, match, ngModel, ngSelect, options, startLoading, stopLoading, timer, trackBy, valuesExpr, viewWatch; + scope.disabledValuesHistory = scope.disabledValuesHistory ? scope.disabledValuesHistory : []; + element = $(element); + element.addClass('localytics-chosen'); + ngSelect = ctrls[0]; + ngModel = ctrls[1]; + match = attr.ngOptions && attr.ngOptions.match(NG_OPTIONS_REGEXP); + valuesExpr = match && $parse(match[7]); + trackBy = match && match[8]; + directiveOptions = scope.$eval(attr.chosen) || {}; + options = angular.copy(config); + angular.extend(options, directiveOptions); + angular.forEach(attr, function(value, key) { + if (indexOf.call(CHOSEN_OPTION_WHITELIST, key) >= 0) { + return attr.$observe(key, function(value) { + var prefix; + prefix = String(element.attr(attr.$attr[key])).slice(0, 2); + options[snakeCase(key)] = prefix === '{{' ? value : scope.$eval(value); + return disableIfEmpty(); + }); + } + }); + startLoading = function() { + return element.addClass('loading').attr('disabled', true).trigger('chosen:updated'); + }; + stopLoading = function() { + element.removeClass('loading'); + if (angular.isDefined(attr.disabled)) { + element.attr('disabled', attr.disabled); + } else { + element.attr('disabled', false); + } + return element.trigger('chosen:updated'); + }; + chosen = null; + empty = false; + initIfNot = function() { + if (!chosen) { + return scope.$evalAsync(function() { + if (!chosen) { + return chosen = element.chosen(options).data('chosen'); + } + }); + } + }; + disableIfEmpty = function() { + if (chosen && empty) { + element.attr('disabled', true); + } + return element.trigger('chosen:updated'); + }; + if (ngModel) { + $render = ngModel.$render; + ngModel.$render = function() { + var isPrimitive, nextValue, previousValue, valueChanged; + initIfNot(); + try { + previousValue = ngSelect.readValue(); + } catch (error) {} + $render(); + try { + nextValue = ngSelect.readValue(); + } catch (error) {} + isPrimitive = !trackBy && !attr.multiple; + valueChanged = isPrimitive ? previousValue !== nextValue : !angular.equals(previousValue, nextValue); + if (valueChanged) { + return element.trigger('chosen:updated'); + } + }; + element.on('chosen:hiding_dropdown', function() { + return scope.$applyAsync(function() { + return ngModel.$setTouched(); + }); + }); + if (attr.multiple) { + viewWatch = function() { + return ngModel.$viewValue; + }; + scope.$watch(viewWatch, ngModel.$render, true); + } + } + attr.$observe('disabled', function() { + return element.trigger('chosen:updated'); + }); + if (attr.ngOptions && ngModel) { + timer = null; + scope.$watchCollection(valuesExpr, function(newVal, oldVal) { + return timer = $timeout(function() { + if (angular.isUndefined(newVal)) { + return startLoading(); + } else { + empty = isEmpty(newVal); + stopLoading(); + return disableIfEmpty(); + } + }); + }); + return scope.$on('$destroy', function(event) { + if (timer != null) { + return $timeout.cancel(timer); + } + }); + } + } + }; + } + ]); + +}).call(this); diff --git a/src/main/resources/static/module/angular-chosen/angular-chosen.min.js b/src/main/resources/static/module/angular-chosen/angular-chosen.min.js new file mode 100644 index 0000000..0fb6bfb --- /dev/null +++ b/src/main/resources/static/module/angular-chosen/angular-chosen.min.js @@ -0,0 +1,7 @@ +/** + * angular-chosen-localytics - Angular Chosen directive is an AngularJS Directive that brings the Chosen jQuery in a Angular way + * @version v1.9.2 + * @link http://github.com/leocaseiro/angular-chosen + * @license MIT + */ +(function(){var e,n=[].indexOf||function(e){for(var n=0,t=this.length;n=0)return c.$observe(t,function(e){var n;return n=String(u.attr(c.$attr[t])).slice(0,2),O[l(t)]="{{"===n?e:o.$eval(e),p()})}),m=function(){return u.addClass("loading").attr("disabled",!0).trigger("chosen:updated")},x=function(){return u.removeClass("loading"),angular.isDefined(c.disabled)?u.attr("disabled",c.disabled):u.attr("disabled",!1),u.trigger("chosen:updated")},h=null,b=!1,y=function(){if(!h)return o.$evalAsync(function(){if(!h)return h=u.chosen(O).data("chosen")})},p=function(){return h&&b&&u.attr("disabled",!0),u.trigger("chosen:updated")},S&&(f=S.$render,S.$render=function(){var e,n,t,r;y();try{t=w.readValue()}catch(i){}f();try{n=w.readValue()}catch(i){}if(e=!T&&!c.multiple,r=e?t!==n:!angular.equals(t,n))return u.trigger("chosen:updated")},u.on("chosen:hiding_dropdown",function(){return o.$applyAsync(function(){return S.$setTouched()})}),c.multiple&&(k=function(){return S.$viewValue},o.$watch(k,S.$render,!0))),c.$observe("disabled",function(){return u.trigger("chosen:updated")}),c.ngOptions&&S)return C=null,o.$watchCollection(V,function(e,n){return C=t(function(){return angular.isUndefined(e)?m():(b=s(e),x(),p())})}),o.$on("$destroy",function(e){if(null!=C)return t.cancel(C)})}}}])}).call(this); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-chosen/spinner.gif b/src/main/resources/static/module/angular-chosen/spinner.gif new file mode 100644 index 0000000..8020e7f Binary files /dev/null and b/src/main/resources/static/module/angular-chosen/spinner.gif differ diff --git a/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.js b/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.js new file mode 100644 index 0000000..5f7ab05 --- /dev/null +++ b/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.js @@ -0,0 +1,260 @@ +/** + * Angular Dynamic Locale - 0.1.32 + * https://github.com/lgalfaso/angular-dynamic-locale + * License: MIT + */ +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module unless amdModuleId is set + define([], function () { + return (factory()); + }); + } else if (typeof exports === 'object') { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(); + } else { + factory(); + } +}(this, function () { +'use strict'; +angular.module('tmh.dynamicLocale', []).config(['$provide', function($provide) { + function makeStateful($delegate) { + $delegate.$stateful = true; + return $delegate; + } + + $provide.decorator('dateFilter', ['$delegate', makeStateful]); + $provide.decorator('numberFilter', ['$delegate', makeStateful]); + $provide.decorator('currencyFilter', ['$delegate', makeStateful]); + +}]) +.constant('tmhDynamicLocale.STORAGE_KEY', 'tmhDynamicLocale.locale') +.provider('tmhDynamicLocale', ['tmhDynamicLocale.STORAGE_KEY', function(STORAGE_KEY) { + + var defaultLocale, + localeLocationPattern = 'angular/i18n/angular-locale_{{locale}}.js', + nodeToAppend, + storageFactory = 'tmhDynamicLocaleStorageCache', + storage, + storageKey = STORAGE_KEY, + promiseCache = {}, + activeLocale, + extraProperties = {}; + + /** + * Loads a script asynchronously + * + * @param {string} url The url for the script + @ @param {function} callback A function to be called once the script is loaded + */ + function loadScript(url, callback, errorCallback, $timeout) { + var script = document.createElement('script'), + element = nodeToAppend ? nodeToAppend : document.getElementsByTagName("body")[0], + removed = false; + + script.type = 'text/javascript'; + if (script.readyState) { // IE + script.onreadystatechange = function () { + if (script.readyState === 'complete' || + script.readyState === 'loaded') { + script.onreadystatechange = null; + $timeout( + function () { + if (removed) return; + removed = true; + element.removeChild(script); + callback(); + }, 30, false); + } + }; + } else { // Others + script.onload = function () { + if (removed) return; + removed = true; + element.removeChild(script); + callback(); + }; + script.onerror = function () { + if (removed) return; + removed = true; + element.removeChild(script); + errorCallback(); + }; + } + script.src = url; + script.async = true; + element.appendChild(script); + } + + /** + * Loads a locale and replaces the properties from the current locale with the new locale information + * + * @param {string} localeUrl The path to the new locale + * @param {Object} $locale The locale at the curent scope + * @param {string} localeId The locale id to load + * @param {Object} $rootScope The application $rootScope + * @param {Object} $q The application $q + * @param {Object} localeCache The current locale cache + * @param {Object} $timeout The application $timeout + */ + function loadLocale(localeUrl, $locale, localeId, $rootScope, $q, localeCache, $timeout) { + + function overrideValues(oldObject, newObject) { + if (activeLocale !== localeId) { + return; + } + angular.forEach(oldObject, function(value, key) { + if (!newObject[key]) { + delete oldObject[key]; + } else if (angular.isArray(newObject[key])) { + oldObject[key].length = newObject[key].length; + } + }); + angular.forEach(newObject, function(value, key) { + if (angular.isArray(newObject[key]) || angular.isObject(newObject[key])) { + if (!oldObject[key]) { + oldObject[key] = angular.isArray(newObject[key]) ? [] : {}; + } + overrideValues(oldObject[key], newObject[key]); + } else { + oldObject[key] = newObject[key]; + } + }); + } + + + if (promiseCache[localeId]) { + activeLocale = localeId; + return promiseCache[localeId]; + } + + var cachedLocale, + deferred = $q.defer(); + if (localeId === activeLocale) { + deferred.resolve($locale); + } else if ((cachedLocale = localeCache.get(localeId))) { + activeLocale = localeId; + $rootScope.$evalAsync(function() { + overrideValues($locale, cachedLocale); + storage.put(storageKey, localeId); + $rootScope.$broadcast('$localeChangeSuccess', localeId, $locale); + deferred.resolve($locale); + }); + } else { + activeLocale = localeId; + promiseCache[localeId] = deferred.promise; + loadScript(localeUrl, function() { + // Create a new injector with the new locale + var localInjector = angular.injector(['ngLocale']), + externalLocale = localInjector.get('$locale'); + + overrideValues($locale, externalLocale); + localeCache.put(localeId, externalLocale); + delete promiseCache[localeId]; + + $rootScope.$applyAsync(function() { + storage.put(storageKey, localeId); + $rootScope.$broadcast('$localeChangeSuccess', localeId, $locale); + deferred.resolve($locale); + }); + }, function() { + delete promiseCache[localeId]; + + $rootScope.$applyAsync(function() { + if (activeLocale === localeId) { + activeLocale = $locale.id; + } + $rootScope.$broadcast('$localeChangeError', localeId); + deferred.reject(localeId); + }); + }, $timeout); + } + return deferred.promise; + } + + this.localeLocationPattern = function(value) { + if (value) { + localeLocationPattern = value; + return this; + } else { + return localeLocationPattern; + } + }; + + this.appendScriptTo = function(nodeElement) { + nodeToAppend = nodeElement; + }; + + this.useStorage = function(storageName) { + storageFactory = storageName; + }; + + this.useCookieStorage = function() { + this.useStorage('$cookieStore'); + }; + + this.defaultLocale = function(value) { + defaultLocale = value; + }; + + this.storageKey = function(value) { + if (value) { + storageKey = value; + return this; + } else { + return storageKey; + } + }; + + this.addLocalePatternValue = function(key, value) { + extraProperties[key] = value; + }; + + this.$get = ['$rootScope', '$injector', '$interpolate', '$locale', '$q', 'tmhDynamicLocaleCache', '$timeout', function($rootScope, $injector, interpolate, locale, $q, tmhDynamicLocaleCache, $timeout) { + var localeLocation = interpolate(localeLocationPattern); + + storage = $injector.get(storageFactory); + $rootScope.$evalAsync(function() { + var initialLocale; + if ((initialLocale = (storage.get(storageKey) || defaultLocale))) { + loadLocaleFn(initialLocale); + } + }); + return { + /** + * @ngdoc method + * @description + * @param {string} value Sets the locale to the new locale. Changing the locale will trigger + * a background task that will retrieve the new locale and configure the current $locale + * instance with the information from the new locale + */ + set: loadLocaleFn, + /** + * @ngdoc method + * @description Returns the configured locale + */ + get: function() { + return activeLocale; + } + }; + + function loadLocaleFn(localeId) { + var baseProperties = {locale: localeId, angularVersion: angular.version.full}; + return loadLocale(localeLocation(angular.extend({}, extraProperties, baseProperties)), locale, localeId, $rootScope, $q, tmhDynamicLocaleCache, $timeout); + } + }]; +}]).provider('tmhDynamicLocaleCache', function() { + this.$get = ['$cacheFactory', function($cacheFactory) { + return $cacheFactory('tmh.dynamicLocales'); + }]; +}).provider('tmhDynamicLocaleStorageCache', function() { + this.$get = ['$cacheFactory', function($cacheFactory) { + return $cacheFactory('tmh.dynamicLocales.store'); + }]; +}).run(['tmhDynamicLocale', angular.noop]); + +return 'tmh.dynamicLocale'; + +})); diff --git a/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.min.js b/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.min.js new file mode 100644 index 0000000..d92ec79 --- /dev/null +++ b/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.min.js @@ -0,0 +1,8 @@ +/** + * Angular Dynamic Locale - 0.1.32 + * https://github.com/lgalfaso/angular-dynamic-locale + * License: MIT + */ + +!function(a,b){"function"==typeof define&&define.amd?define([],function(){return b()}):"object"==typeof exports?module.exports=b():b()}(this,function(){"use strict";return angular.module("tmh.dynamicLocale",[]).config(["$provide",function(a){function b(a){return a.$stateful=!0,a}a.decorator("dateFilter",["$delegate",b]),a.decorator("numberFilter",["$delegate",b]),a.decorator("currencyFilter",["$delegate",b])}]).constant("tmhDynamicLocale.STORAGE_KEY","tmhDynamicLocale.locale").provider("tmhDynamicLocale",["tmhDynamicLocale.STORAGE_KEY",function(a){function b(a,b,c,d){var f=document.createElement("script"),g=e?e:document.getElementsByTagName("body")[0],h=!1;f.type="text/javascript",f.readyState?f.onreadystatechange=function(){("complete"===f.readyState||"loaded"===f.readyState)&&(f.onreadystatechange=null,d(function(){h||(h=!0,g.removeChild(f),b())},30,!1))}:(f.onload=function(){h||(h=!0,g.removeChild(f),b())},f.onerror=function(){h||(h=!0,g.removeChild(f),c())}),f.src=a,f.async=!0,g.appendChild(f)}function c(a,c,d,e,h,i,l){function m(a,b){g===d&&(angular.forEach(a,function(c,d){b[d]?angular.isArray(b[d])&&(a[d].length=b[d].length):delete a[d]}),angular.forEach(b,function(c,d){angular.isArray(b[d])||angular.isObject(b[d])?(a[d]||(a[d]=angular.isArray(b[d])?[]:{}),m(a[d],b[d])):a[d]=b[d]}))}if(k[d])return g=d,k[d];var n,o=h.defer();return d===g?o.resolve(c):(n=i.get(d))?(g=d,e.$evalAsync(function(){m(c,n),f.put(j,d),e.$broadcast("$localeChangeSuccess",d,c),o.resolve(c)})):(g=d,k[d]=o.promise,b(a,function(){var a=angular.injector(["ngLocale"]),b=a.get("$locale");m(c,b),i.put(d,b),delete k[d],e.$applyAsync(function(){f.put(j,d),e.$broadcast("$localeChangeSuccess",d,c),o.resolve(c)})},function(){delete k[d],e.$applyAsync(function(){g===d&&(g=c.id),e.$broadcast("$localeChangeError",d),o.reject(d)})},l)),o.promise}var d,e,f,g,h="angular/i18n/angular-locale_{{locale}}.js",i="tmhDynamicLocaleStorageCache",j=a,k={},l={};this.localeLocationPattern=function(a){return a?(h=a,this):h},this.appendScriptTo=function(a){e=a},this.useStorage=function(a){i=a},this.useCookieStorage=function(){this.useStorage("$cookieStore")},this.defaultLocale=function(a){d=a},this.storageKey=function(a){return a?(j=a,this):j},this.addLocalePatternValue=function(a,b){l[a]=b},this.$get=["$rootScope","$injector","$interpolate","$locale","$q","tmhDynamicLocaleCache","$timeout",function(a,b,e,k,m,n,o){function p(b){var d={locale:b,angularVersion:angular.version.full};return c(q(angular.extend({},l,d)),k,b,a,m,n,o)}var q=e(h);return f=b.get(i),a.$evalAsync(function(){var a;(a=f.get(j)||d)&&p(a)}),{set:p,get:function(){return g}}}]}]).provider("tmhDynamicLocaleCache",function(){this.$get=["$cacheFactory",function(a){return a("tmh.dynamicLocales")}]}).provider("tmhDynamicLocaleStorageCache",function(){this.$get=["$cacheFactory",function(a){return a("tmh.dynamicLocales.store")}]}).run(["tmhDynamicLocale",angular.noop]),"tmh.dynamicLocale"}); +//# sourceMappingURL=tmhDynamicLocale.min.js.map \ No newline at end of file diff --git a/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.min.js.map b/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.min.js.map new file mode 100644 index 0000000..fb7fcfe --- /dev/null +++ b/src/main/resources/static/module/angular-dynamic-locale/tmhDynamicLocale.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tmhDynamicLocale.min.js","sources":["../src/tmhDynamicLocale.js"],"names":["root","factory","define","amd","exports","module","this","angular","config","$provide","makeStateful","$delegate","$stateful","decorator","constant","provider","STORAGE_KEY","loadScript","url","callback","errorCallback","$timeout","script","document","createElement","element","nodeToAppend","getElementsByTagName","removed","type","readyState","onreadystatechange","removeChild","onload","onerror","src","async","appendChild","loadLocale","localeUrl","$locale","localeId","$rootScope","$q","localeCache","overrideValues","oldObject","newObject","activeLocale","forEach","value","key","isArray","length","isObject","promiseCache","cachedLocale","deferred","defer","resolve","get","$evalAsync","storage","put","storageKey","$broadcast","promise","localInjector","injector","externalLocale","$applyAsync","id","reject","defaultLocale","localeLocationPattern","storageFactory","extraProperties","appendScriptTo","nodeElement","useStorage","storageName","useCookieStorage","addLocalePatternValue","$get","$injector","interpolate","locale","tmhDynamicLocaleCache","loadLocaleFn","baseProperties","angularVersion","version","full","localeLocation","extend","initialLocale","set","$cacheFactory","run","noop"],"mappings":"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"} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-filter/angular-filter.js b/src/main/resources/static/module/angular-filter/angular-filter.js new file mode 100644 index 0000000..dbafd79 --- /dev/null +++ b/src/main/resources/static/module/angular-filter/angular-filter.js @@ -0,0 +1,2287 @@ +/** + * Bunch of useful filters for angularJS(with no external dependencies!) + * @version v0.5.7 - 2015-10-04 * @link https://github.com/a8m/angular-filter + * @author Ariel Mashraki + * @license MIT License, http://www.opensource.org/licenses/MIT + */ +(function ( window, angular, undefined ) { +/*jshint globalstrict:true*/ +'use strict'; + +var isDefined = angular.isDefined, + isUndefined = angular.isUndefined, + isFunction = angular.isFunction, + isString = angular.isString, + isNumber = angular.isNumber, + isObject = angular.isObject, + isArray = angular.isArray, + forEach = angular.forEach, + extend = angular.extend, + copy = angular.copy, + equals = angular.equals; + + +/** + * @description + * get an object and return array of values + * @param object + * @returns {Array} + */ +function toArray(object) { + return isArray(object) + ? object + : Object.keys(object).map(function(key) { + return object[key]; + }); +} + +/** + * @param value + * @returns {boolean} + */ +function isNull(value) { + return value === null; +} + +/** + * @description + * return if object contains partial object + * @param partial{object} + * @param object{object} + * @returns {boolean} + */ +function objectContains(partial, object) { + var keys = Object.keys(partial); + + return keys.map(function(el) { + return (object[el] !== undefined) && (object[el] == partial[el]); + }).indexOf(false) == -1; + +} + +/** + * @description + * search for approximate pattern in string + * @param word + * @param pattern + * @returns {*} + */ +function hasApproxPattern(word, pattern) { + if(pattern === '') + return word; + + var index = word.indexOf(pattern.charAt(0)); + + if(index === -1) + return false; + + return hasApproxPattern(word.substr(index+1), pattern.substr(1)) +} + +/** + * @description + * return the first n element of an array, + * if expression provided, is returns as long the expression return truthy + * @param array + * @param n {number} + * @param expression {$parse} + * @return array or single object + */ +function getFirstMatches(array, n, expression) { + var count = 0; + + return array.filter(function(elm) { + var rest = isDefined(expression) ? (count < n && expression(elm)) : count < n; + count = rest ? count+1 : count; + + return rest; + }); +} +/** + * Polyfill to ECMA6 String.prototype.contains + */ +if (!String.prototype.contains) { + String.prototype.contains = function() { + return String.prototype.indexOf.apply(this, arguments) !== -1; + }; +} + +/** + * @param num {Number} + * @param decimal {Number} + * @param $math + * @returns {Number} + */ +function convertToDecimal(num, decimal, $math){ + return $math.round(num * $math.pow(10,decimal)) / ($math.pow(10,decimal)); +} + +/** + * @description + * Get an object, and return an array composed of it's properties names(nested too). + * @param obj {Object} + * @param stack {Array} + * @param parent {String} + * @returns {Array} + * @example + * parseKeys({ a:1, b: { c:2, d: { e: 3 } } }) ==> ["a", "b.c", "b.d.e"] + */ +function deepKeys(obj, stack, parent) { + stack = stack || []; + var keys = Object.keys(obj); + + keys.forEach(function(el) { + //if it's a nested object + if(isObject(obj[el]) && !isArray(obj[el])) { + //concatenate the new parent if exist + var p = parent ? parent + '.' + el : parent; + deepKeys(obj[el], stack, p || el); + } else { + //create and save the key + var key = parent ? parent + '.' + el : el; + stack.push(key) + } + }); + return stack +} + +/** + * @description + * Test if given object is a Scope instance + * @param obj + * @returns {Boolean} + */ +function isScope(obj) { + return obj && obj.$evalAsync && obj.$watch; +} + +/** + * @ngdoc filter + * @name a8m.angular + * @kind function + * + * @description + * reference to angular function + */ + +angular.module('a8m.angular', []) + + .filter('isUndefined', function () { + return function (input) { + return angular.isUndefined(input); + } + }) + .filter('isDefined', function() { + return function (input) { + return angular.isDefined(input); + } + }) + .filter('isFunction', function() { + return function (input) { + return angular.isFunction(input); + } + }) + .filter('isString', function() { + return function (input) { + return angular.isString(input) + } + }) + .filter('isNumber', function() { + return function (input) { + return angular.isNumber(input); + } + }) + .filter('isArray', function() { + return function (input) { + return angular.isArray(input); + } + }) + .filter('isObject', function() { + return function (input) { + return angular.isObject(input); + } + }) + .filter('isEqual', function() { + return function (o1, o2) { + return angular.equals(o1, o2); + } + }); + +/** + * @ngdoc filter + * @name a8m.conditions + * @kind function + * + * @description + * reference to math conditions + */ + angular.module('a8m.conditions', []) + + .filter({ + isGreaterThan : isGreaterThanFilter, + '>' : isGreaterThanFilter, + + isGreaterThanOrEqualTo : isGreaterThanOrEqualToFilter, + '>=' : isGreaterThanOrEqualToFilter, + + isLessThan : isLessThanFilter, + '<' : isLessThanFilter, + + isLessThanOrEqualTo : isLessThanOrEqualToFilter, + '<=' : isLessThanOrEqualToFilter, + + isEqualTo : isEqualToFilter, + '==' : isEqualToFilter, + + isNotEqualTo : isNotEqualToFilter, + '!=' : isNotEqualToFilter, + + isIdenticalTo : isIdenticalToFilter, + '===' : isIdenticalToFilter, + + isNotIdenticalTo : isNotIdenticalToFilter, + '!==' : isNotIdenticalToFilter + }); + + function isGreaterThanFilter() { + return function (input, check) { + return input > check; + }; + } + + function isGreaterThanOrEqualToFilter() { + return function (input, check) { + return input >= check; + }; + } + + function isLessThanFilter() { + return function (input, check) { + return input < check; + }; + } + + function isLessThanOrEqualToFilter() { + return function (input, check) { + return input <= check; + }; + } + + function isEqualToFilter() { + return function (input, check) { + return input == check; + }; + } + + function isNotEqualToFilter() { + return function (input, check) { + return input != check; + }; + } + + function isIdenticalToFilter() { + return function (input, check) { + return input === check; + }; + } + + function isNotIdenticalToFilter() { + return function (input, check) { + return input !== check; + }; + } +/** + * @ngdoc filter + * @name isNull + * @kind function + * + * @description + * checks if value is null or not + * @return Boolean + */ +angular.module('a8m.is-null', []) + .filter('isNull', function () { + return function(input) { + return isNull(input); + } + }); + +/** + * @ngdoc filter + * @name after-where + * @kind function + * + * @description + * get a collection and properties object, and returns all of the items + * in the collection after the first that found with the given properties. + * + */ +angular.module('a8m.after-where', []) + .filter('afterWhere', function() { + return function (collection, object) { + + collection = isObject(collection) + ? toArray(collection) + : collection; + + if(!isArray(collection) || isUndefined(object)) return collection; + + var index = collection.map( function( elm ) { + return objectContains(object, elm); + }).indexOf( true ); + + return collection.slice((index === -1) ? 0 : index); + } + }); + +/** + * @ngdoc filter + * @name after + * @kind function + * + * @description + * get a collection and specified count, and returns all of the items + * in the collection after the specified count. + * + */ + +angular.module('a8m.after', []) + .filter('after', function() { + return function (collection, count) { + collection = isObject(collection) + ? toArray(collection) + : collection; + + return (isArray(collection)) + ? collection.slice(count) + : collection; + } + }); + +/** + * @ngdoc filter + * @name before-where + * @kind function + * + * @description + * get a collection and properties object, and returns all of the items + * in the collection before the first that found with the given properties. + */ +angular.module('a8m.before-where', []) + .filter('beforeWhere', function() { + return function (collection, object) { + + collection = isObject(collection) + ? toArray(collection) + : collection; + + if(!isArray(collection) || isUndefined(object)) return collection; + + var index = collection.map( function( elm ) { + return objectContains(object, elm); + }).indexOf( true ); + + return collection.slice(0, (index === -1) ? collection.length : ++index); + } + }); + +/** + * @ngdoc filter + * @name before + * @kind function + * + * @description + * get a collection and specified count, and returns all of the items + * in the collection before the specified count. + */ +angular.module('a8m.before', []) + .filter('before', function() { + return function (collection, count) { + collection = isObject(collection) + ? toArray(collection) + : collection; + + return (isArray(collection)) + ? collection.slice(0, (!count) ? count : --count) + : collection; + } + }); + +/** + * @ngdoc filter + * @name chunkBy + * @kind function + * + * @description + * Collect data into fixed-length chunks or blocks + */ + +angular.module('a8m.chunk-by', ['a8m.filter-watcher']) + .filter('chunkBy', ['filterWatcher', function (filterWatcher) { + return function (array, n, fillVal) { + + return filterWatcher.isMemoized('chunkBy', arguments) || + filterWatcher.memoize('chunkBy', arguments, this, + _chunkBy(array, n, fillVal)); + /** + * @description + * Get array with size `n` in `val` inside it. + * @param n + * @param val + * @returns {Array} + */ + function fill(n, val) { + var ret = []; + while (n--) ret[n] = val; + return ret; + } + + function _chunkBy(array, n, fillVal) { + if (!isArray(array)) return array; + return array.map(function (el, i, self) { + i = i * n; + el = self.slice(i, i + n); + return !isUndefined(fillVal) && el.length < n + ? el.concat(fill(n - el.length, fillVal)) + : el; + }).slice(0, Math.ceil(array.length / n)); + } + } + }]); + +/** + * @ngdoc filter + * @name concat + * @kind function + * + * @description + * get (array/object, object/array) and return merged collection + */ +angular.module('a8m.concat', []) + .filter('concat', [function () { + return function (collection, joined) { + + if (isUndefined(joined)) return collection; + + if (isArray(collection)) { + return isObject(joined) + ? collection.concat(toArray(joined)) + : collection.concat(joined); + } + + if (isObject(collection)) { + var array = toArray(collection); + return (isObject(joined)) + ? array.concat(toArray(joined)) + : array.concat(joined); + } + return collection; + }; + } +]); + +/** + * @ngdoc filter + * @name contains + * @kind function + * + * @description + * Checks if given expression is present in one or more object in the collection + */ +angular.module('a8m.contains', []) + .filter({ + contains: ['$parse', containsFilter], + some: ['$parse', containsFilter] + }); + +function containsFilter($parse) { + return function (collection, expression) { + + collection = isObject(collection) ? toArray(collection) : collection; + + if(!isArray(collection) || isUndefined(expression)) { + return false; + } + + return collection.some(function(elm) { + return (isObject(elm) || isFunction(expression)) + ? $parse(expression)(elm) + : elm === expression; + }); + + } + } + +/** + * @ngdoc filter + * @name countBy + * @kind function + * + * @description + * Sorts a list into groups and returns a count for the number of objects in each group. + */ + +angular.module('a8m.count-by', []) + + .filter('countBy', [ '$parse', function ( $parse ) { + return function (collection, property) { + + var result = {}, + get = $parse(property), + prop; + + collection = (isObject(collection)) ? toArray(collection) : collection; + + if(!isArray(collection) || isUndefined(property)) { + return collection; + } + + collection.forEach( function( elm ) { + prop = get(elm); + + if(!result[prop]) { + result[prop] = 0; + } + + result[prop]++; + }); + + return result; + } + }]); + +/** + * @ngdoc filter + * @name defaults + * @kind function + * + * @description + * defaultsFilter allows to specify a default fallback value for properties that resolve to undefined. + */ +angular.module('a8m.defaults', []) + .filter('defaults', ['$parse', function( $parse ) { + return function(collection, defaults) { + + collection = isObject(collection) ? toArray(collection) : collection; + + if(!isArray(collection) || !isObject(defaults)) { + return collection; + } + + var keys = deepKeys(defaults); + + collection.forEach(function(elm) { + //loop through all the keys + keys.forEach(function(key) { + var getter = $parse(key); + var setter = getter.assign; + //if it's not exist + if(isUndefined(getter(elm))) { + //get from defaults, and set to the returned object + setter(elm, getter(defaults)) + } + }); + }); + + return collection; + } + }]); +/** + * @ngdoc filter + * @name every + * @kind function + * + * @description + * Checks if given expression is present in all members in the collection + * + */ +angular.module('a8m.every', []) + .filter('every', ['$parse', function($parse) { + return function (collection, expression) { + collection = isObject(collection) ? toArray(collection) : collection; + + if(!isArray(collection) || isUndefined(expression)) { + return true; + } + + return collection.every( function(elm) { + return (isObject(elm) || isFunction(expression)) + ? $parse(expression)(elm) + : elm === expression; + }); + } + }]); + +/** + * @ngdoc filter + * @name filterBy + * @kind function + * + * @description + * filter by specific properties, avoid the rest + */ +angular.module('a8m.filter-by', []) + .filter('filterBy', ['$parse', function( $parse ) { + return function(collection, properties, search) { + var comparator; + + search = (isString(search) || isNumber(search)) ? + String(search).toLowerCase() : undefined; + + collection = isObject(collection) ? toArray(collection) : collection; + + if(!isArray(collection) || isUndefined(search)) { + return collection; + } + + return collection.filter(function(elm) { + return properties.some(function(prop) { + + /** + * check if there is concatenate properties + * example: + * object: { first: 'foo', last:'bar' } + * filterBy: ['first + last'] => search by full name(i.e 'foo bar') + */ + if(!~prop.indexOf('+')) { + comparator = $parse(prop)(elm) + } else { + var propList = prop.replace(new RegExp('\\s', 'g'), '').split('+'); + comparator = propList.reduce(function(prev, cur, index) { + return (index === 1) ? $parse(prev)(elm) + ' ' + $parse(cur)(elm) : + prev + ' ' + $parse(cur)(elm); + }); + } + + return (isString(comparator) || isNumber(comparator)) + ? String(comparator).toLowerCase().contains(search) + : false; + }); + }); + } + }]); + +/** + * @ngdoc filter + * @name first + * @kind function + * + * @description + * Gets the first element or first n elements of an array + * if callback is provided, is returns as long the callback return truthy + */ +angular.module('a8m.first', []) + .filter('first', ['$parse', function( $parse ) { + return function(collection) { + var n + , getter + , args; + + collection = isObject(collection) + ? toArray(collection) + : collection; + + if(!isArray(collection)) { + return collection; + } + + args = Array.prototype.slice.call(arguments, 1); + n = (isNumber(args[0])) ? args[0] : 1; + getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; + + return (args.length) ? getFirstMatches(collection, n,(getter) ? $parse(getter) : getter) : + collection[0]; + } + }]); + +/** + * @ngdoc filter + * @name flatten + * @kind function + * + * @description + * Flattens a nested array (the nesting can be to any depth). + * If you pass shallow, the array will only be flattened a single level + */ +angular.module('a8m.flatten', []) + .filter('flatten', function () { + return function(collection, shallow) { + + shallow = shallow || false; + collection = isObject(collection) + ? toArray(collection) + : collection; + + if(!isArray(collection)) { + return collection; + } + + return !shallow + ? flatten(collection, 0) + : [].concat.apply([], collection); + } + }); + +/** + * flatten nested array (the nesting can be to any depth). + * @param array {Array} + * @param i {int} + * @returns {Array} + * @private + */ +function flatten(array, i) { + i = i || 0; + + if(i >= array.length) + return array; + + if(isArray(array[i])) { + return flatten(array.slice(0,i) + .concat(array[i], array.slice(i+1)), i); + } + return flatten(array, i+1); +} + +/** + * @ngdoc filter + * @name fuzzyByKey + * @kind function + * + * @description + * fuzzy string searching by key + */ +angular.module('a8m.fuzzy-by', []) + .filter('fuzzyBy', ['$parse', function ( $parse ) { + return function (collection, property, search, csensitive) { + + var sensitive = csensitive || false, + prop, getter; + + collection = isObject(collection) ? toArray(collection) : collection; + + if(!isArray(collection) || isUndefined(property) + || isUndefined(search)) { + return collection; + } + + getter = $parse(property); + + return collection.filter(function(elm) { + + prop = getter(elm); + if(!isString(prop)) { + return false; + } + + prop = (sensitive) ? prop : prop.toLowerCase(); + search = (sensitive) ? search : search.toLowerCase(); + + return hasApproxPattern(prop, search) !== false + }) + } + + }]); +/** + * @ngdoc filter + * @name fuzzy + * @kind function + * + * @description + * fuzzy string searching for array of strings, objects + */ +angular.module('a8m.fuzzy', []) + .filter('fuzzy', function () { + return function (collection, search, csensitive) { + var sensitive = csensitive || false; + collection = isObject(collection) ? toArray(collection) : collection; + + if(!isArray(collection) || isUndefined(search)) { + return collection; + } + + search = (sensitive) ? search : search.toLowerCase(); + + return collection.filter(function(elm) { + if(isString(elm)) { + elm = (sensitive) ? elm : elm.toLowerCase(); + return hasApproxPattern(elm, search) !== false + } + return (isObject(elm)) ? _hasApproximateKey(elm, search) : false; + }); + + /** + * checks if object has key{string} that match + * to fuzzy search pattern + * @param object + * @param search + * @returns {boolean} + * @private + */ + function _hasApproximateKey(object, search) { + var properties = Object.keys(object), + prop, flag; + return 0 < properties.filter(function (elm) { + prop = object[elm]; + + //avoid iteration if we found some key that equal[performance] + if(flag) return true; + + if (isString(prop)) { + prop = (sensitive) ? prop : prop.toLowerCase(); + return flag = (hasApproxPattern(prop, search) !== false); + } + + return false; + + }).length; + } + } + }); + +/** + * @ngdoc filter + * @name groupBy + * @kind function + * + * @description + * Create an object composed of keys generated from the result of running each element of a collection, + * each key is an array of the elements. + */ + +angular.module('a8m.group-by', [ 'a8m.filter-watcher' ]) + .filter('groupBy', [ '$parse', 'filterWatcher', function ( $parse, filterWatcher ) { + return function (collection, property) { + + if(!isObject(collection) || isUndefined(property)) { + return collection; + } + + return filterWatcher.isMemoized('groupBy', arguments) || + filterWatcher.memoize('groupBy', arguments, this, + _groupBy(collection, $parse(property))); + + /** + * groupBy function + * @param collection + * @param getter + * @returns {{}} + */ + function _groupBy(collection, getter) { + var result = {}; + var prop; + + forEach( collection, function( elm ) { + prop = getter(elm); + + if(!result[prop]) { + result[prop] = []; + } + result[prop].push(elm); + }); + return result; + } + } + }]); + +/** + * @ngdoc filter + * @name isEmpty + * @kind function + * + * @description + * get collection or string and return if it empty + */ +angular.module('a8m.is-empty', []) + .filter('isEmpty', function () { + return function(collection) { + return isObject(collection) + ? !toArray(collection).length + : !collection.length; + } + }); + +/** + * @ngdoc filter + * @name join + * @kind function + * + * @description + * join a collection by a provided delimiter (space by default) + */ +angular.module('a8m.join', []) + .filter('join', function () { + return function (input, delimiter) { + if (isUndefined(input) || !isArray(input)) { + return input; + } + if (isUndefined(delimiter)) delimiter = ' '; + + return input.join(delimiter); + }; + }) +; + +/** + * @ngdoc filter + * @name last + * @kind function + * + * @description + * Gets the last element or last n elements of an array + * if callback is provided, is returns as long the callback return truthy + */ +angular.module('a8m.last', []) + .filter('last', ['$parse', function( $parse ) { + return function(collection) { + var n + , getter + , args + //cuz reverse change our src collection + //and we don't want side effects + , reversed = copy(collection); + + reversed = isObject(reversed) + ? toArray(reversed) + : reversed; + + if(!isArray(reversed)) { + return reversed; + } + + args = Array.prototype.slice.call(arguments, 1); + n = (isNumber(args[0])) ? args[0] : 1; + getter = (!isNumber(args[0])) ? args[0] : (!isNumber(args[1])) ? args[1] : undefined; + + return (args.length) + //send reversed collection as arguments, and reverse it back as result + ? getFirstMatches(reversed.reverse(), n,(getter) ? $parse(getter) : getter).reverse() + //get the last element + : reversed[reversed.length-1]; + } + }]); + +/** + * @ngdoc filter + * @name map + * @kind function + * + * @description + * Returns a new collection of the results of each expression execution. + */ +angular.module('a8m.map', []) + .filter('map', ['$parse', function($parse) { + return function (collection, expression) { + + collection = isObject(collection) + ? toArray(collection) + : collection; + + if(!isArray(collection) || isUndefined(expression)) { + return collection; + } + + return collection.map(function (elm) { + return $parse(expression)(elm); + }); + } + }]); + +/** + * @ngdoc filter + * @name omit + * @kind function + * + * @description + * filter collection by expression + */ + +angular.module('a8m.omit', []) + + .filter('omit', ['$parse', function($parse) { + return function (collection, expression) { + + collection = isObject(collection) + ? toArray(collection) + : collection; + + if(!isArray(collection) || isUndefined(expression)) { + return collection; + } + + return collection.filter(function (elm) { + return !($parse(expression)(elm)); + }); + } + }]); + +/** + * @ngdoc filter + * @name pick + * @kind function + * + * @description + * filter collection by expression + */ + +angular.module('a8m.pick', []) + + .filter('pick', ['$parse', function($parse) { + return function (collection, expression) { + + collection = isObject(collection) + ? toArray(collection) + : collection; + + if(!isArray(collection) || isUndefined(expression)) { + return collection; + } + + return collection.filter(function (elm) { + return $parse(expression)(elm); + }); + } + }]); + +/** + * @ngdoc filter + * @name range + * @kind function + * + * @description + * rangeFilter provides some support for a for loop using numbers + */ +angular.module('a8m.range', []) + .filter('range', function () { + return function (input, total) { + for (var i = 0; i < parseInt(total); i++) { + input.push(i); + } + return input; + }; + }); +/** + * @ngdoc filter + * @name removeWith + * @kind function + * + * @description + * get collection and properties object, and removed elements + * with this properties + */ + +angular.module('a8m.remove-with', []) + .filter('removeWith', function() { + return function (collection, object) { + + if(isUndefined(object)) { + return collection; + } + collection = isObject(collection) + ? toArray(collection) + : collection; + + return collection.filter(function (elm) { + return !objectContains(object, elm); + }); + } + }); + + +/** + * @ngdoc filter + * @name remove + * @kind function + * + * @description + * remove specific members from collection + */ + +angular.module('a8m.remove', []) + + .filter('remove', function () { + return function (collection) { + collection = isObject(collection) ? toArray(collection) : collection; + var args = Array.prototype.slice.call(arguments, 1); + + if(!isArray(collection)) { + return collection; + } + + return collection.filter( function( member ) { + return !args.some(function(nest) { + return equals(nest, member); + }) + }); + } + }); + +/** + * @ngdoc filter + * @name reverse + * @kind function + * + * @description + * Reverses a string or collection + */ +angular.module('a8m.reverse', []) + .filter('reverse',[ function () { + return function (input) { + input = isObject(input) ? toArray(input) : input; + + if(isString(input)) { + return input.split('').reverse().join(''); + } + + return isArray(input) + ? input.slice().reverse() + : input; + } + }]); + +/** + * @ngdoc filter + * @name searchField + * @kind function + * + * @description + * for each member, join several strings field and add them to + * new field called 'searchField' (use for search filtering) + */ +angular.module('a8m.search-field', []) + .filter('searchField', ['$parse', function ($parse) { + return function (collection) { + + var get, field; + + collection = isObject(collection) ? toArray(collection) : collection; + + var args = Array.prototype.slice.call(arguments, 1); + + if(!isArray(collection) || !args.length) { + return collection; + } + + return collection.map(function(member) { + + field = args.map(function(field) { + get = $parse(field); + return get(member); + }).join(' '); + + return extend(member, { searchField: field }); + }); + } + }]); + +/** + * @ngdoc filter + * @name toArray + * @kind function + * + * @description + * Convert objects into stable arrays. + * if addKey set to true,the filter also attaches a new property + * $key to the value containing the original key that was used in + * the object we are iterating over to reference the property + */ +angular.module('a8m.to-array', []) + .filter('toArray', function() { + return function (collection, addKey) { + + if(!isObject(collection)) { + return collection; + } + + return !addKey + ? toArray(collection) + : Object.keys(collection).map(function (key) { + return extend(collection[key], { $key: key }); + }); + } + }); + +/** + * @ngdoc filter + * @name unique/uniq + * @kind function + * + * @description + * get collection and filter duplicate members + * if uniqueFilter get a property(nested to) as argument it's + * filter by this property as unique identifier + */ + +angular.module('a8m.unique', []) + .filter({ + unique: ['$parse', uniqFilter], + uniq: ['$parse', uniqFilter] + }); + +function uniqFilter($parse) { + return function (collection, property) { + + collection = isObject(collection) ? toArray(collection) : collection; + + if (!isArray(collection)) { + return collection; + } + + //store all unique identifiers + var uniqueItems = [], + get = $parse(property); + + return (isUndefined(property)) + //if it's kind of primitive array + ? collection.filter(function (elm, pos, self) { + return self.indexOf(elm) === pos; + }) + //else compare with equals + : collection.filter(function (elm) { + var prop = get(elm); + if(some(uniqueItems, prop)) { + return false; + } + uniqueItems.push(prop); + return true; + }); + + //checked if the unique identifier is already exist + function some(array, member) { + if(isUndefined(member)) { + return false; + } + return array.some(function(el) { + return equals(el, member); + }); + } + } +} + +/** + * @ngdoc filter + * @name where + * @kind function + * + * @description + * of each element in a collection to the given properties object, + * returning an array of all elements that have equivalent property values. + * + */ +angular.module('a8m.where', []) + .filter('where', function() { + return function (collection, object) { + if(isUndefined(object)) return collection; + collection = isObject(collection) + ? toArray(collection) + : collection; + + return collection.filter(function (elm) { + return objectContains(object, elm); + }); + } + }); + +/** + * @ngdoc filter + * @name xor + * @kind function + * + * @description + * Exclusive or filter by expression + */ + +angular.module('a8m.xor', []) + + .filter('xor', ['$parse', function($parse) { + return function (col1, col2, expression) { + + expression = expression || false; + + col1 = isObject(col1) ? toArray(col1) : col1; + col2 = isObject(col2) ? toArray(col2) : col2; + + if(!isArray(col1) || !isArray(col2)) return col1; + + return col1.concat(col2) + .filter(function(elm) { + return !(some(elm, col1) && some(elm, col2)); + }); + + function some(el, col) { + var getter = $parse(expression); + return col.some(function(dElm) { + return expression + ? equals(getter(dElm), getter(el)) + : equals(dElm, el); + }); + } + } + }]); + +/** + * @ngdoc filter + * @name formatBytes + * @kind function + * + * @description + * Convert bytes into appropriate display + * 1024 bytes => 1 KB + */ +angular.module('a8m.math.byteFmt', ['a8m.math']) + .filter('byteFmt', ['$math', function ($math) { + return function (bytes, decimal) { + + if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && + isNumber(bytes) && isFinite(bytes)) { + if(bytes < 1024) { // within 1 KB so B + return convertToDecimal(bytes, decimal, $math) + ' B'; + } else if(bytes < 1048576) { // within 1 MB so KB + return convertToDecimal((bytes / 1024), decimal, $math) + ' KB'; + } else if(bytes < 1073741824){ // within 1 GB so MB + return convertToDecimal((bytes / 1048576), decimal, $math) + ' MB'; + } else { // GB or more + return convertToDecimal((bytes / 1073741824), decimal, $math) + ' GB'; + } + + } + return "NaN"; + } + }]); +/** + * @ngdoc filter + * @name degrees + * @kind function + * + * @description + * Convert angle from radians to degrees + */ +angular.module('a8m.math.degrees', ['a8m.math']) + .filter('degrees', ['$math', function ($math) { + return function (radians, decimal) { + // if decimal is not an integer greater than -1, we cannot do. quit with error "NaN" + // if degrees is not a real number, we cannot do also. quit with error "NaN" + if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && + isNumber(radians) && isFinite(radians)) { + var degrees = (radians * 180) / $math.PI; + return $math.round(degrees * $math.pow(10,decimal)) / ($math.pow(10,decimal)); + } else { + return "NaN"; + } + } + }]); + + + +/** + * @ngdoc filter + * @name formatBytes + * @kind function + * + * @description + * Convert bytes into appropriate display + * 1024 kilobytes => 1 MB + */ +angular.module('a8m.math.kbFmt', ['a8m.math']) + .filter('kbFmt', ['$math', function ($math) { + return function (bytes, decimal) { + + if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && + isNumber(bytes) && isFinite(bytes)) { + if(bytes < 1024) { // within 1 MB so KB + return convertToDecimal(bytes, decimal, $math) + ' KB'; + } else if(bytes < 1048576) { // within 1 GB so MB + return convertToDecimal((bytes / 1024), decimal, $math) + ' MB'; + } else { + return convertToDecimal((bytes / 1048576), decimal, $math) + ' GB'; + } + } + return "NaN"; + } + }]); +/** + * @ngdoc module + * @name math + * @description + * reference to global Math object + */ +angular.module('a8m.math', []) + .factory('$math', ['$window', function ($window) { + return $window.Math; + }]); + +/** + * @ngdoc filter + * @name max + * @kind function + * + * @description + * Math.max will get an array and return the max value. if an expression + * is provided, will return max value by expression. + */ +angular.module('a8m.math.max', ['a8m.math']) + .filter('max', ['$math', '$parse', function ($math, $parse) { + return function (input, expression) { + + if(!isArray(input)) { + return input; + } + return isUndefined(expression) + ? $math.max.apply($math, input) + : input[indexByMax(input, expression)]; + }; + + /** + * @private + * @param array + * @param exp + * @returns {number|*|Number} + */ + function indexByMax(array, exp) { + var mappedArray = array.map(function(elm){ + return $parse(exp)(elm); + }); + return mappedArray.indexOf($math.max.apply($math, mappedArray)); + } + }]); +/** + * @ngdoc filter + * @name min + * @kind function + * + * @description + * Math.min will get an array and return the min value. if an expression + * is provided, will return min value by expression. + */ +angular.module('a8m.math.min', ['a8m.math']) + .filter('min', ['$math', '$parse', function ($math, $parse) { + return function (input, expression) { + + if(!isArray(input)) { + return input; + } + return isUndefined(expression) + ? $math.min.apply($math, input) + : input[indexByMin(input, expression)]; + }; + + /** + * @private + * @param array + * @param exp + * @returns {number|*|Number} + */ + function indexByMin(array, exp) { + var mappedArray = array.map(function(elm){ + return $parse(exp)(elm); + }); + return mappedArray.indexOf($math.min.apply($math, mappedArray)); + } + }]); +/** + * @ngdoc filter + * @name Percent + * @kind function + * + * @description + * percentage between two numbers + */ +angular.module('a8m.math.percent', ['a8m.math']) + .filter('percent', ['$math', '$window', function ($math, $window) { + return function (input, divided, round) { + + var divider = isString(input) ? $window.Number(input) : input; + divided = divided || 100; + round = round || false; + + if (!isNumber(divider) || $window.isNaN(divider)) return input; + + return round + ? $math.round((divider / divided) * 100) + : (divider / divided) * 100; + } + }]); + +/** + * @ngdoc filter + * @name toRadians + * @kind function + * + * @description + * Convert angle from degrees to radians + */ +angular.module('a8m.math.radians', ['a8m.math']) + .filter('radians', ['$math', function ($math) { + return function (degrees, decimal) { + // if decimal is not an integer greater than -1, we cannot do. quit with error "NaN" + // if degrees is not a real number, we cannot do also. quit with error "NaN" + if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && + isNumber(degrees) && isFinite(degrees)) { + var radians = (degrees * 3.14159265359) / 180; + return $math.round(radians * $math.pow(10,decimal)) / ($math.pow(10,decimal)); + } + return "NaN"; + } + }]); + + + +/** + * @ngdoc filter + * @name Radix + * @kind function + * + * @description + * converting decimal numbers to different bases(radix) + */ +angular.module('a8m.math.radix', []) + .filter('radix', function () { + return function (input, radix) { + var RANGE = /^[2-9]$|^[1-2]\d$|^3[0-6]$/; + + if(!isNumber(input) || !RANGE.test(radix)) { + return input; + } + + return input.toString(radix).toUpperCase(); + } + }); + +/** + * @ngdoc filter + * @name formatBytes + * @kind function + * + * @description + * Convert number into abbreviations. + * i.e: K for one thousand, M for Million, B for billion + * e.g: number of users:235,221, decimal:1 => 235.2 K + */ +angular.module('a8m.math.shortFmt', ['a8m.math']) + .filter('shortFmt', ['$math', function ($math) { + return function (number, decimal) { + if(isNumber(decimal) && isFinite(decimal) && decimal%1===0 && decimal >= 0 && + isNumber(number) && isFinite(number)){ + if(number < 1e3) { + return number; + } else if(number < 1e6) { + return convertToDecimal((number / 1e3), decimal, $math) + ' K'; + } else if(number < 1e9){ + return convertToDecimal((number / 1e6), decimal, $math) + ' M'; + } else { + return convertToDecimal((number / 1e9), decimal, $math) + ' B'; + } + + } + return "NaN"; + } + }]); +/** + * @ngdoc filter + * @name sum + * @kind function + * + * @description + * Sum up all values within an array + */ +angular.module('a8m.math.sum', []) + .filter('sum', function () { + return function (input, initial) { + return !isArray(input) + ? input + : input.reduce(function(prev, curr) { + return prev + curr; + }, initial || 0); + } + }); + +/** + * @ngdoc filter + * @name endsWith + * @kind function + * + * @description + * checks whether string ends with the ends parameter. + */ +angular.module('a8m.ends-with', []) + + .filter('endsWith', function () { + return function (input, ends, csensitive) { + + var sensitive = csensitive || false, + position; + + if(!isString(input) || isUndefined(ends)) { + return input; + } + + input = (sensitive) ? input : input.toLowerCase(); + position = input.length - ends.length; + + return input.indexOf((sensitive) ? ends : ends.toLowerCase(), position) !== -1; + } + }); + +/** + * @ngdoc filter + * @name latinize + * @kind function + * + * @description + * remove accents/diacritics from a string + */ +angular.module('a8m.latinize', []) + .filter('latinize',[ function () { + var defaultDiacriticsRemovalap = [ + {'base':'A', 'letters':'\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F'}, + {'base':'AA','letters':'\uA732'}, + {'base':'AE','letters':'\u00C6\u01FC\u01E2'}, + {'base':'AO','letters':'\uA734'}, + {'base':'AU','letters':'\uA736'}, + {'base':'AV','letters':'\uA738\uA73A'}, + {'base':'AY','letters':'\uA73C'}, + {'base':'B', 'letters':'\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181'}, + {'base':'C', 'letters':'\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E'}, + {'base':'D', 'letters':'\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779'}, + {'base':'DZ','letters':'\u01F1\u01C4'}, + {'base':'Dz','letters':'\u01F2\u01C5'}, + {'base':'E', 'letters':'\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E'}, + {'base':'F', 'letters':'\u0046\u24BB\uFF26\u1E1E\u0191\uA77B'}, + {'base':'G', 'letters':'\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E'}, + {'base':'H', 'letters':'\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D'}, + {'base':'I', 'letters':'\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197'}, + {'base':'J', 'letters':'\u004A\u24BF\uFF2A\u0134\u0248'}, + {'base':'K', 'letters':'\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2'}, + {'base':'L', 'letters':'\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780'}, + {'base':'LJ','letters':'\u01C7'}, + {'base':'Lj','letters':'\u01C8'}, + {'base':'M', 'letters':'\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C'}, + {'base':'N', 'letters':'\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4'}, + {'base':'NJ','letters':'\u01CA'}, + {'base':'Nj','letters':'\u01CB'}, + {'base':'O', 'letters':'\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C'}, + {'base':'OI','letters':'\u01A2'}, + {'base':'OO','letters':'\uA74E'}, + {'base':'OU','letters':'\u0222'}, + {'base':'OE','letters':'\u008C\u0152'}, + {'base':'oe','letters':'\u009C\u0153'}, + {'base':'P', 'letters':'\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754'}, + {'base':'Q', 'letters':'\u0051\u24C6\uFF31\uA756\uA758\u024A'}, + {'base':'R', 'letters':'\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782'}, + {'base':'S', 'letters':'\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784'}, + {'base':'T', 'letters':'\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786'}, + {'base':'TZ','letters':'\uA728'}, + {'base':'U', 'letters':'\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244'}, + {'base':'V', 'letters':'\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245'}, + {'base':'VY','letters':'\uA760'}, + {'base':'W', 'letters':'\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72'}, + {'base':'X', 'letters':'\u0058\u24CD\uFF38\u1E8A\u1E8C'}, + {'base':'Y', 'letters':'\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE'}, + {'base':'Z', 'letters':'\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762'}, + {'base':'a', 'letters':'\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250'}, + {'base':'aa','letters':'\uA733'}, + {'base':'ae','letters':'\u00E6\u01FD\u01E3'}, + {'base':'ao','letters':'\uA735'}, + {'base':'au','letters':'\uA737'}, + {'base':'av','letters':'\uA739\uA73B'}, + {'base':'ay','letters':'\uA73D'}, + {'base':'b', 'letters':'\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253'}, + {'base':'c', 'letters':'\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184'}, + {'base':'d', 'letters':'\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A'}, + {'base':'dz','letters':'\u01F3\u01C6'}, + {'base':'e', 'letters':'\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD'}, + {'base':'f', 'letters':'\u0066\u24D5\uFF46\u1E1F\u0192\uA77C'}, + {'base':'g', 'letters':'\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F'}, + {'base':'h', 'letters':'\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265'}, + {'base':'hv','letters':'\u0195'}, + {'base':'i', 'letters':'\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131'}, + {'base':'j', 'letters':'\u006A\u24D9\uFF4A\u0135\u01F0\u0249'}, + {'base':'k', 'letters':'\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3'}, + {'base':'l', 'letters':'\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747'}, + {'base':'lj','letters':'\u01C9'}, + {'base':'m', 'letters':'\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F'}, + {'base':'n', 'letters':'\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5'}, + {'base':'nj','letters':'\u01CC'}, + {'base':'o', 'letters':'\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275'}, + {'base':'oi','letters':'\u01A3'}, + {'base':'ou','letters':'\u0223'}, + {'base':'oo','letters':'\uA74F'}, + {'base':'p','letters':'\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755'}, + {'base':'q','letters':'\u0071\u24E0\uFF51\u024B\uA757\uA759'}, + {'base':'r','letters':'\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783'}, + {'base':'s','letters':'\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B'}, + {'base':'t','letters':'\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787'}, + {'base':'tz','letters':'\uA729'}, + {'base':'u','letters': '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289'}, + {'base':'v','letters':'\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C'}, + {'base':'vy','letters':'\uA761'}, + {'base':'w','letters':'\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73'}, + {'base':'x','letters':'\u0078\u24E7\uFF58\u1E8B\u1E8D'}, + {'base':'y','letters':'\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF'}, + {'base':'z','letters':'\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763'} + ]; + + var diacriticsMap = {}; + for (var i = 0; i < defaultDiacriticsRemovalap.length; i++) { + var letters = defaultDiacriticsRemovalap[i].letters.split(""); + for (var j = 0; j < letters.length ; j++){ + diacriticsMap[letters[j]] = defaultDiacriticsRemovalap[i].base; + } + } + + // "what?" version ... http://jsperf.com/diacritics/12 + function removeDiacritics (str) { + return str.replace(/[^\u0000-\u007E]/g, function(a){ + return diacriticsMap[a] || a; + }); + } + + return function (input) { + + return isString(input) + ? removeDiacritics(input) + : input; + } + }]); + +/** + * @ngdoc filter + * @name ltrim + * @kind function + * + * @description + * Left trim. Similar to trimFilter, but only for left side. + */ +angular.module('a8m.ltrim', []) + .filter('ltrim', function () { + return function(input, chars) { + + var trim = chars || '\\s'; + + return isString(input) + ? input.replace(new RegExp('^' + trim + '+'), '') + : input; + } + }); + +/** + * @ngdoc filter + * @name match + * @kind function + * + * @description + * Return the matched pattern in a string. + */ +angular.module('a8m.match', []) + .filter('match', function () { + return function (input, pattern, flag) { + + var reg = new RegExp(pattern, flag); + + return isString(input) + ? input.match(reg) + : null; + } + }); + +/** + * @ngdoc filter + * @name repeat + * @kind function + * + * @description + * Repeats a string n times + */ +angular.module('a8m.repeat', []) + .filter('repeat',[ function () { + return function (input, n, separator) { + + var times = ~~n; + + if(!isString(input)) { + return input; + } + + return !times + ? input + : strRepeat(input, --n, separator || ''); + } + }]); + +/** + * Repeats a string n times with given separator + * @param str string to repeat + * @param n number of times + * @param sep separator + * @returns {*} + */ +function strRepeat(str, n, sep) { + if(!n) { + return str; + } + return str + sep + strRepeat(str, --n, sep); +} +/** +* @ngdoc filter +* @name rtrim +* @kind function +* +* @description +* Right trim. Similar to trimFilter, but only for right side. +*/ +angular.module('a8m.rtrim', []) + .filter('rtrim', function () { + return function(input, chars) { + + var trim = chars || '\\s'; + + return isString(input) + ? input.replace(new RegExp(trim + '+$'), '') + : input; + } + }); + +/** + * @ngdoc filter + * @name slugify + * @kind function + * + * @description + * remove spaces from string, replace with "-" or given argument + */ +angular.module('a8m.slugify', []) + .filter('slugify',[ function () { + return function (input, sub) { + + var replace = (isUndefined(sub)) ? '-' : sub; + + return isString(input) + ? input.toLowerCase().replace(/\s+/g, replace) + : input; + } + }]); + +/** + * @ngdoc filter + * @name startWith + * @kind function + * + * @description + * checks whether string starts with the starts parameter. + */ +angular.module('a8m.starts-with', []) + .filter('startsWith', function () { + return function (input, start, csensitive) { + + var sensitive = csensitive || false; + + if(!isString(input) || isUndefined(start)) { + return input; + } + + input = (sensitive) ? input : input.toLowerCase(); + + return !input.indexOf((sensitive) ? start : start.toLowerCase()); + } + }); + +/** + * @ngdoc filter + * @name stringular + * @kind function + * + * @description + * get string with {n} and replace match with enumeration values + */ +angular.module('a8m.stringular', []) + .filter('stringular', function () { + return function(input) { + + var args = Array.prototype.slice.call(arguments, 1); + + return input.replace(/{(\d+)}/g, function (match, number) { + return isUndefined(args[number]) ? match : args[number]; + }); + } + }); + +/** + * @ngdoc filter + * @name stripTags + * @kind function + * + * @description + * strip html tags from string + */ +angular.module('a8m.strip-tags', []) + .filter('stripTags', function () { + return function(input) { + return isString(input) + ? input.replace(/<\S[^><]*>/g, '') + : input; + } + }); + +/** + * @ngdoc filter + * @name test + * @kind function + * + * @description + * test if a string match a pattern. + */ +angular.module('a8m.test', []) + .filter('test', function () { + return function (input, pattern, flag) { + + var reg = new RegExp(pattern, flag); + + return isString(input) + ? reg.test(input) + : input; + } + }); + +/** + * @ngdoc filter + * @name trim + * @kind function + * + * @description + * Strip whitespace (or other characters) from the beginning and end of a string + */ +angular.module('a8m.trim', []) + .filter('trim', function () { + return function(input, chars) { + + var trim = chars || '\\s'; + + return isString(input) + ? input.replace(new RegExp('^' + trim + '+|' + trim + '+$', 'g'), '') + : input; + } + }); + +/** + * @ngdoc filter + * @name truncate + * @kind function + * + * @description + * truncates a string given a specified length, providing a custom string to denote an omission. + */ +angular.module('a8m.truncate', []) + .filter('truncate', function () { + return function(input, length, suffix, preserve) { + + length = isUndefined(length) ? input.length : length; + preserve = preserve || false; + suffix = suffix || ''; + + if(!isString(input) || (input.length <= length)) return input; + + return input.substring(0, (preserve) + ? ((input.indexOf(' ', length) === -1) ? input.length : input.indexOf(' ', length)) + : length) + suffix; + }; + }); + +/** + * @ngdoc filter + * @name ucfirst + * @kind function + * + * @description + * ucfirst + */ +angular.module('a8m.ucfirst', []) + .filter('ucfirst', [function() { + return function(input) { + return isString(input) + ? input + .split(' ') + .map(function (ch) { + return ch.charAt(0).toUpperCase() + ch.substring(1); + }) + .join(' ') + : input; + } + }]); + +/** + * @ngdoc filter + * @name uriComponentEncode + * @kind function + * + * @description + * get string as parameter and return encoded string + */ +angular.module('a8m.uri-component-encode', []) + .filter('uriComponentEncode',['$window', function ($window) { + return function (input) { + return isString(input) + ? $window.encodeURIComponent(input) + : input; + } + }]); + +/** + * @ngdoc filter + * @name uriEncode + * @kind function + * + * @description + * get string as parameter and return encoded string + */ +angular.module('a8m.uri-encode', []) + .filter('uriEncode',['$window', function ($window) { + return function (input) { + return isString(input) + ? $window.encodeURI(input) + : input; + } + }]); + +/** + * @ngdoc filter + * @name wrap + * @kind function + * + * @description + * Wrap a string with another string + */ +angular.module('a8m.wrap', []) + .filter('wrap', function () { + return function(input, wrap, ends) { + return isString(input) && isDefined(wrap) + ? [wrap, input, ends || wrap].join('') + : input; + } + }); + +/** + * @ngdoc provider + * @name filterWatcher + * @kind function + * + * @description + * store specific filters result in $$cache, based on scope life time(avoid memory leak). + * on scope.$destroy remove it's cache from $$cache container + */ + +angular.module('a8m.filter-watcher', []) + .provider('filterWatcher', function() { + + this.$get = ['$window', '$rootScope', function($window, $rootScope) { + + /** + * Cache storing + * @type {Object} + */ + var $$cache = {}; + + /** + * Scope listeners container + * scope.$destroy => remove all cache keys + * bind to current scope. + * @type {Object} + */ + var $$listeners = {}; + + /** + * $timeout without triggering the digest cycle + * @type {function} + */ + var $$timeout = $window.setTimeout; + + /** + * @description + * get `HashKey` string based on the given arguments. + * @param fName + * @param args + * @returns {string} + */ + function getHashKey(fName, args) { + function replacerFactory() { + var cache = []; + return function(key, val) { + if(isObject(val) && !isNull(val)) { + if (~cache.indexOf(val)) return '[Circular]'; + cache.push(val) + } + if($window == val) return '$WINDOW'; + if($window.document == val) return '$DOCUMENT'; + if(isScope(val)) return '$SCOPE'; + return val; + } + } + return [fName, JSON.stringify(args, replacerFactory())] + .join('#') + .replace(/"/g,''); + } + + /** + * @description + * fir on $scope.$destroy, + * remove cache based scope from `$$cache`, + * and remove itself from `$$listeners` + * @param event + */ + function removeCache(event) { + var id = event.targetScope.$id; + forEach($$listeners[id], function(key) { + delete $$cache[key]; + }); + delete $$listeners[id]; + } + + /** + * @description + * for angular version that greater than v.1.3.0 + * it clear cache when the digest cycle is end. + */ + function cleanStateless() { + $$timeout(function() { + if(!$rootScope.$$phase) + $$cache = {}; + }, 2000); + } + + /** + * @description + * Store hashKeys in $$listeners container + * on scope.$destroy, remove them all(bind an event). + * @param scope + * @param hashKey + * @returns {*} + */ + function addListener(scope, hashKey) { + var id = scope.$id; + if(isUndefined($$listeners[id])) { + scope.$on('$destroy', removeCache); + $$listeners[id] = []; + } + return $$listeners[id].push(hashKey); + } + + /** + * @description + * return the `cacheKey` or undefined. + * @param filterName + * @param args + * @returns {*} + */ + function $$isMemoized(filterName, args) { + var hashKey = getHashKey(filterName, args); + return $$cache[hashKey]; + } + + /** + * @description + * store `result` in `$$cache` container, based on the hashKey. + * add $destroy listener and return result + * @param filterName + * @param args + * @param scope + * @param result + * @returns {*} + */ + function $$memoize(filterName, args, scope, result) { + var hashKey = getHashKey(filterName, args); + //store result in `$$cache` container + $$cache[hashKey] = result; + // for angular versions that less than 1.3 + // add to `$destroy` listener, a cleaner callback + if(isScope(scope)) { + addListener(scope, hashKey); + } else { + cleanStateless(); + } + return result; + } + + return { + isMemoized: $$isMemoized, + memoize: $$memoize + } + }]; + }); + + +/** + * @ngdoc module + * @name angular.filters + * @description + * Bunch of useful filters for angularJS + */ + +angular.module('angular.filter', [ + + 'a8m.ucfirst', + 'a8m.uri-encode', + 'a8m.uri-component-encode', + 'a8m.slugify', + 'a8m.latinize', + 'a8m.strip-tags', + 'a8m.stringular', + 'a8m.truncate', + 'a8m.starts-with', + 'a8m.ends-with', + 'a8m.wrap', + 'a8m.trim', + 'a8m.ltrim', + 'a8m.rtrim', + 'a8m.repeat', + 'a8m.test', + 'a8m.match', + + 'a8m.to-array', + 'a8m.concat', + 'a8m.contains', + 'a8m.unique', + 'a8m.is-empty', + 'a8m.after', + 'a8m.after-where', + 'a8m.before', + 'a8m.before-where', + 'a8m.defaults', + 'a8m.where', + 'a8m.reverse', + 'a8m.remove', + 'a8m.remove-with', + 'a8m.group-by', + 'a8m.count-by', + 'a8m.chunk-by', + 'a8m.search-field', + 'a8m.fuzzy-by', + 'a8m.fuzzy', + 'a8m.omit', + 'a8m.pick', + 'a8m.every', + 'a8m.filter-by', + 'a8m.xor', + 'a8m.map', + 'a8m.first', + 'a8m.last', + 'a8m.flatten', + 'a8m.join', + 'a8m.range', + + 'a8m.math', + 'a8m.math.max', + 'a8m.math.min', + 'a8m.math.percent', + 'a8m.math.radix', + 'a8m.math.sum', + 'a8m.math.degrees', + 'a8m.math.radians', + 'a8m.math.byteFmt', + 'a8m.math.kbFmt', + 'a8m.math.shortFmt', + + 'a8m.angular', + 'a8m.conditions', + 'a8m.is-null', + + 'a8m.filter-watcher' +]); +})( window, window.angular ); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-filter/angular-filter.min.js b/src/main/resources/static/module/angular-filter/angular-filter.min.js new file mode 100644 index 0000000..11714a5 --- /dev/null +++ b/src/main/resources/static/module/angular-filter/angular-filter.min.js @@ -0,0 +1,6 @@ +/** + * Bunch of useful filters for angularJS(with no external dependencies!) + * @version v0.5.7 - 2015-10-04 * @link https://github.com/a8m/angular-filter + * @author Ariel Mashraki + * @license MIT License, http://www.opensource.org/licenses/MIT + */!function(a,b,c){"use strict";function d(a){return D(a)?a:Object.keys(a).map(function(b){return a[b]})}function e(a){return null===a}function f(a,b){var d=Object.keys(a);return-1==d.map(function(d){return b[d]!==c&&b[d]==a[d]}).indexOf(!1)}function g(a,b){if(""===b)return a;var c=a.indexOf(b.charAt(0));return-1===c?!1:g(a.substr(c+1),b.substr(1))}function h(a,b,c){var d=0;return a.filter(function(a){var e=x(c)?b>d&&c(a):b>d;return d=e?d+1:d,e})}function i(a,b,c){return c.round(a*c.pow(10,b))/c.pow(10,b)}function j(a,b,c){b=b||[];var d=Object.keys(a);return d.forEach(function(d){if(C(a[d])&&!D(a[d])){var e=c?c+"."+d:c;j(a[d],b,e||d)}else{var f=c?c+"."+d:d;b.push(f)}}),b}function k(a){return a&&a.$evalAsync&&a.$watch}function l(){return function(a,b){return a>b}}function m(){return function(a,b){return a>=b}}function n(){return function(a,b){return b>a}}function o(){return function(a,b){return b>=a}}function p(){return function(a,b){return a==b}}function q(){return function(a,b){return a!=b}}function r(){return function(a,b){return a===b}}function s(){return function(a,b){return a!==b}}function t(a){return function(b,c){return b=C(b)?d(b):b,!D(b)||y(c)?!1:b.some(function(b){return C(b)||z(c)?a(c)(b):b===c})}}function u(a,b){return b=b||0,b>=a.length?a:D(a[b])?u(a.slice(0,b).concat(a[b],a.slice(b+1)),b):u(a,b+1)}function v(a){return function(b,c){function e(a,b){return y(b)?!1:a.some(function(a){return H(a,b)})}if(b=C(b)?d(b):b,!D(b))return b;var f=[],g=a(c);return y(c)?b.filter(function(a,b,c){return c.indexOf(a)===b}):b.filter(function(a){var b=g(a);return e(f,b)?!1:(f.push(b),!0)})}}function w(a,b,c){return b?a+c+w(a,--b,c):a}var x=b.isDefined,y=b.isUndefined,z=b.isFunction,A=b.isString,B=b.isNumber,C=b.isObject,D=b.isArray,E=b.forEach,F=b.extend,G=b.copy,H=b.equals;String.prototype.contains||(String.prototype.contains=function(){return-1!==String.prototype.indexOf.apply(this,arguments)}),b.module("a8m.angular",[]).filter("isUndefined",function(){return function(a){return b.isUndefined(a)}}).filter("isDefined",function(){return function(a){return b.isDefined(a)}}).filter("isFunction",function(){return function(a){return b.isFunction(a)}}).filter("isString",function(){return function(a){return b.isString(a)}}).filter("isNumber",function(){return function(a){return b.isNumber(a)}}).filter("isArray",function(){return function(a){return b.isArray(a)}}).filter("isObject",function(){return function(a){return b.isObject(a)}}).filter("isEqual",function(){return function(a,c){return b.equals(a,c)}}),b.module("a8m.conditions",[]).filter({isGreaterThan:l,">":l,isGreaterThanOrEqualTo:m,">=":m,isLessThan:n,"<":n,isLessThanOrEqualTo:o,"<=":o,isEqualTo:p,"==":p,isNotEqualTo:q,"!=":q,isIdenticalTo:r,"===":r,isNotIdenticalTo:s,"!==":s}),b.module("a8m.is-null",[]).filter("isNull",function(){return function(a){return e(a)}}),b.module("a8m.after-where",[]).filter("afterWhere",function(){return function(a,b){if(a=C(a)?d(a):a,!D(a)||y(b))return a;var c=a.map(function(a){return f(b,a)}).indexOf(!0);return a.slice(-1===c?0:c)}}),b.module("a8m.after",[]).filter("after",function(){return function(a,b){return a=C(a)?d(a):a,D(a)?a.slice(b):a}}),b.module("a8m.before-where",[]).filter("beforeWhere",function(){return function(a,b){if(a=C(a)?d(a):a,!D(a)||y(b))return a;var c=a.map(function(a){return f(b,a)}).indexOf(!0);return a.slice(0,-1===c?a.length:++c)}}),b.module("a8m.before",[]).filter("before",function(){return function(a,b){return a=C(a)?d(a):a,D(a)?a.slice(0,b?--b:b):a}}),b.module("a8m.chunk-by",["a8m.filter-watcher"]).filter("chunkBy",["filterWatcher",function(a){return function(b,c,d){function e(a,b){for(var c=[];a--;)c[a]=b;return c}function f(a,b,c){return D(a)?a.map(function(a,d,f){return d*=b,a=f.slice(d,d+b),!y(c)&&a.length=0&&B(b)&&isFinite(b)?1024>b?i(b,c,a)+" B":1048576>b?i(b/1024,c,a)+" KB":1073741824>b?i(b/1048576,c,a)+" MB":i(b/1073741824,c,a)+" GB":"NaN"}}]),b.module("a8m.math.degrees",["a8m.math"]).filter("degrees",["$math",function(a){return function(b,c){if(B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)){var d=180*b/a.PI;return a.round(d*a.pow(10,c))/a.pow(10,c)}return"NaN"}}]),b.module("a8m.math.kbFmt",["a8m.math"]).filter("kbFmt",["$math",function(a){return function(b,c){return B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)?1024>b?i(b,c,a)+" KB":1048576>b?i(b/1024,c,a)+" MB":i(b/1048576,c,a)+" GB":"NaN"}}]),b.module("a8m.math",[]).factory("$math",["$window",function(a){return a.Math}]),b.module("a8m.math.max",["a8m.math"]).filter("max",["$math","$parse",function(a,b){function c(c,d){var e=c.map(function(a){return b(d)(a)});return e.indexOf(a.max.apply(a,e))}return function(b,d){return D(b)?y(d)?a.max.apply(a,b):b[c(b,d)]:b}}]),b.module("a8m.math.min",["a8m.math"]).filter("min",["$math","$parse",function(a,b){function c(c,d){var e=c.map(function(a){return b(d)(a)});return e.indexOf(a.min.apply(a,e))}return function(b,d){return D(b)?y(d)?a.min.apply(a,b):b[c(b,d)]:b}}]),b.module("a8m.math.percent",["a8m.math"]).filter("percent",["$math","$window",function(a,b){return function(c,d,e){var f=A(c)?b.Number(c):c;return d=d||100,e=e||!1,!B(f)||b.isNaN(f)?c:e?a.round(f/d*100):f/d*100}}]),b.module("a8m.math.radians",["a8m.math"]).filter("radians",["$math",function(a){return function(b,c){if(B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)){var d=3.14159265359*b/180;return a.round(d*a.pow(10,c))/a.pow(10,c)}return"NaN"}}]),b.module("a8m.math.radix",[]).filter("radix",function(){return function(a,b){var c=/^[2-9]$|^[1-2]\d$|^3[0-6]$/;return B(a)&&c.test(b)?a.toString(b).toUpperCase():a}}),b.module("a8m.math.shortFmt",["a8m.math"]).filter("shortFmt",["$math",function(a){return function(b,c){return B(c)&&isFinite(c)&&c%1===0&&c>=0&&B(b)&&isFinite(b)?1e3>b?b:1e6>b?i(b/1e3,c,a)+" K":1e9>b?i(b/1e6,c,a)+" M":i(b/1e9,c,a)+" B":"NaN"}}]),b.module("a8m.math.sum",[]).filter("sum",function(){return function(a,b){return D(a)?a.reduce(function(a,b){return a+b},b||0):a}}),b.module("a8m.ends-with",[]).filter("endsWith",function(){return function(a,b,c){var d,e=c||!1;return!A(a)||y(b)?a:(a=e?a:a.toLowerCase(),d=a.length-b.length,-1!==a.indexOf(e?b:b.toLowerCase(),d))}}),b.module("a8m.latinize",[]).filter("latinize",[function(){function a(a){return a.replace(/[^\u0000-\u007E]/g,function(a){return c[a]||a})}for(var b=[{base:"A",letters:"AⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ"},{base:"AA",letters:"Ꜳ"},{base:"AE",letters:"ÆǼǢ"},{base:"AO",letters:"Ꜵ"},{base:"AU",letters:"Ꜷ"},{base:"AV",letters:"ꜸꜺ"},{base:"AY",letters:"Ꜽ"},{base:"B",letters:"BⒷBḂḄḆɃƂƁ"},{base:"C",letters:"CⒸCĆĈĊČÇḈƇȻꜾ"},{base:"D",letters:"DⒹDḊĎḌḐḒḎĐƋƊƉꝹ"},{base:"DZ",letters:"DZDŽ"},{base:"Dz",letters:"DzDž"},{base:"E",letters:"EⒺEÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ"},{base:"F",letters:"FⒻFḞƑꝻ"},{base:"G",letters:"GⒼGǴĜḠĞĠǦĢǤƓꞠꝽꝾ"},{base:"H",letters:"HⒽHĤḢḦȞḤḨḪĦⱧⱵꞍ"},{base:"I",letters:"IⒾIÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ"},{base:"J",letters:"JⒿJĴɈ"},{base:"K",letters:"KⓀKḰǨḲĶḴƘⱩꝀꝂꝄꞢ"},{base:"L",letters:"LⓁLĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ"},{base:"LJ",letters:"LJ"},{base:"Lj",letters:"Lj"},{base:"M",letters:"MⓂMḾṀṂⱮƜ"},{base:"N",letters:"NⓃNǸŃÑṄŇṆŅṊṈȠƝꞐꞤ"},{base:"NJ",letters:"NJ"},{base:"Nj",letters:"Nj"},{base:"O",letters:"OⓄOÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ"},{base:"OI",letters:"Ƣ"},{base:"OO",letters:"Ꝏ"},{base:"OU",letters:"Ȣ"},{base:"OE",letters:"ŒŒ"},{base:"oe",letters:"œœ"},{base:"P",letters:"PⓅPṔṖƤⱣꝐꝒꝔ"},{base:"Q",letters:"QⓆQꝖꝘɊ"},{base:"R",letters:"RⓇRŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ"},{base:"S",letters:"SⓈSẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ"},{base:"T",letters:"TⓉTṪŤṬȚŢṰṮŦƬƮȾꞆ"},{base:"TZ",letters:"Ꜩ"},{base:"U",letters:"UⓊUÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ"},{base:"V",letters:"VⓋVṼṾƲꝞɅ"},{base:"VY",letters:"Ꝡ"},{base:"W",letters:"WⓌWẀẂŴẆẄẈⱲ"},{base:"X",letters:"XⓍXẊẌ"},{base:"Y",letters:"YⓎYỲÝŶỸȲẎŸỶỴƳɎỾ"},{base:"Z",letters:"ZⓏZŹẐŻŽẒẔƵȤⱿⱫꝢ"},{base:"a",letters:"aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ"},{base:"aa",letters:"ꜳ"},{base:"ae",letters:"æǽǣ"},{base:"ao",letters:"ꜵ"},{base:"au",letters:"ꜷ"},{base:"av",letters:"ꜹꜻ"},{base:"ay",letters:"ꜽ"},{base:"b",letters:"bⓑbḃḅḇƀƃɓ"},{base:"c",letters:"cⓒcćĉċčçḉƈȼꜿↄ"},{base:"d",letters:"dⓓdḋďḍḑḓḏđƌɖɗꝺ"},{base:"dz",letters:"dzdž"},{base:"e",letters:"eⓔeèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ"},{base:"f",letters:"fⓕfḟƒꝼ"},{base:"g",letters:"gⓖgǵĝḡğġǧģǥɠꞡᵹꝿ"},{base:"h",letters:"hⓗhĥḣḧȟḥḩḫẖħⱨⱶɥ"},{base:"hv",letters:"ƕ"},{base:"i",letters:"iⓘiìíîĩīĭïḯỉǐȉȋịįḭɨı"},{base:"j",letters:"jⓙjĵǰɉ"},{base:"k",letters:"kⓚkḱǩḳķḵƙⱪꝁꝃꝅꞣ"},{base:"l",letters:"lⓛlŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ"},{base:"lj",letters:"lj"},{base:"m",letters:"mⓜmḿṁṃɱɯ"},{base:"n",letters:"nⓝnǹńñṅňṇņṋṉƞɲʼnꞑꞥ"},{base:"nj",letters:"nj"},{base:"o",letters:"oⓞoòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ"},{base:"oi",letters:"ƣ"},{base:"ou",letters:"ȣ"},{base:"oo",letters:"ꝏ"},{base:"p",letters:"pⓟpṕṗƥᵽꝑꝓꝕ"},{base:"q",letters:"qⓠqɋꝗꝙ"},{base:"r",letters:"rⓡrŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ"},{base:"s",letters:"sⓢsßśṥŝṡšṧṣṩșşȿꞩꞅẛ"},{base:"t",letters:"tⓣtṫẗťṭțţṱṯŧƭʈⱦꞇ"},{base:"tz",letters:"ꜩ"},{base:"u",letters:"uⓤuùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ"},{base:"v",letters:"vⓥvṽṿʋꝟʌ"},{base:"vy",letters:"ꝡ"},{base:"w",letters:"wⓦwẁẃŵẇẅẘẉⱳ"},{base:"x",letters:"xⓧxẋẍ"},{base:"y",letters:"yⓨyỳýŷỹȳẏÿỷẙỵƴɏỿ"},{base:"z",letters:"zⓩzźẑżžẓẕƶȥɀⱬꝣ"}],c={},d=0;d<]*>/g,""):a}}),b.module("a8m.test",[]).filter("test",function(){return function(a,b,c){var d=new RegExp(b,c);return A(a)?d.test(a):a}}),b.module("a8m.trim",[]).filter("trim",function(){return function(a,b){var c=b||"\\s";return A(a)?a.replace(new RegExp("^"+c+"+|"+c+"+$","g"),""):a}}),b.module("a8m.truncate",[]).filter("truncate",function(){return function(a,b,c,d){return b=y(b)?a.length:b,d=d||!1,c=c||"",!A(a)||a.length<=b?a:a.substring(0,d?-1===a.indexOf(" ",b)?a.length:a.indexOf(" ",b):b)+c}}),b.module("a8m.ucfirst",[]).filter("ucfirst",[function(){return function(a){return A(a)?a.split(" ").map(function(a){return a.charAt(0).toUpperCase()+a.substring(1)}).join(" "):a}}]),b.module("a8m.uri-component-encode",[]).filter("uriComponentEncode",["$window",function(a){return function(b){return A(b)?a.encodeURIComponent(b):b}}]),b.module("a8m.uri-encode",[]).filter("uriEncode",["$window",function(a){return function(b){return A(b)?a.encodeURI(b):b}}]),b.module("a8m.wrap",[]).filter("wrap",function(){return function(a,b,c){return A(a)&&x(b)?[b,a,c||b].join(""):a}}),b.module("a8m.filter-watcher",[]).provider("filterWatcher",function(){this.$get=["$window","$rootScope",function(a,b){function c(b,c){function d(){var b=[];return function(c,d){if(C(d)&&!e(d)){if(~b.indexOf(d))return"[Circular]";b.push(d)}return a==d?"$WINDOW":a.document==d?"$DOCUMENT":k(d)?"$SCOPE":d}}return[b,JSON.stringify(c,d())].join("#").replace(/"/g,"")}function d(a){var b=a.targetScope.$id;E(l[b],function(a){delete j[a]}),delete l[b]}function f(){m(function(){b.$$phase||(j={})},2e3)}function g(a,b){var c=a.$id;return y(l[c])&&(a.$on("$destroy",d),l[c]=[]),l[c].push(b)}function h(a,b){var d=c(a,b);return j[d]}function i(a,b,d,e){var h=c(a,b);return j[h]=e,k(d)?g(d,h):f(),e}var j={},l={},m=a.setTimeout;return{isMemoized:h,memoize:i}}]}),b.module("angular.filter",["a8m.ucfirst","a8m.uri-encode","a8m.uri-component-encode","a8m.slugify","a8m.latinize","a8m.strip-tags","a8m.stringular","a8m.truncate","a8m.starts-with","a8m.ends-with","a8m.wrap","a8m.trim","a8m.ltrim","a8m.rtrim","a8m.repeat","a8m.test","a8m.match","a8m.to-array","a8m.concat","a8m.contains","a8m.unique","a8m.is-empty","a8m.after","a8m.after-where","a8m.before","a8m.before-where","a8m.defaults","a8m.where","a8m.reverse","a8m.remove","a8m.remove-with","a8m.group-by","a8m.count-by","a8m.chunk-by","a8m.search-field","a8m.fuzzy-by","a8m.fuzzy","a8m.omit","a8m.pick","a8m.every","a8m.filter-by","a8m.xor","a8m.map","a8m.first","a8m.last","a8m.flatten","a8m.join","a8m.range","a8m.math","a8m.math.max","a8m.math.min","a8m.math.percent","a8m.math.radix","a8m.math.sum","a8m.math.degrees","a8m.math.radians","a8m.math.byteFmt","a8m.math.kbFmt","a8m.math.shortFmt","a8m.angular","a8m.conditions","a8m.is-null","a8m.filter-watcher"])}(window,window.angular); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-loading-bar/loading-bar.css b/src/main/resources/static/module/angular-loading-bar/loading-bar.css new file mode 100644 index 0000000..72408d1 --- /dev/null +++ b/src/main/resources/static/module/angular-loading-bar/loading-bar.css @@ -0,0 +1,110 @@ +/*! + * angular-loading-bar v0.9.0 + * https://chieffancypants.github.io/angular-loading-bar + * Copyright (c) 2016 Wes Cruver + * License: MIT + */ + +/* Make clicks pass-through */ +#loading-bar, +#loading-bar-spinner { + pointer-events: none; + -webkit-pointer-events: none; + -webkit-transition: 350ms linear all; + -moz-transition: 350ms linear all; + -o-transition: 350ms linear all; + transition: 350ms linear all; +} + +#loading-bar.ng-enter, +#loading-bar.ng-leave.ng-leave-active, +#loading-bar-spinner.ng-enter, +#loading-bar-spinner.ng-leave.ng-leave-active { + opacity: 0; +} + +#loading-bar.ng-enter.ng-enter-active, +#loading-bar.ng-leave, +#loading-bar-spinner.ng-enter.ng-enter-active, +#loading-bar-spinner.ng-leave { + opacity: 1; +} + +#loading-bar .bar { + -webkit-transition: width 350ms; + -moz-transition: width 350ms; + -o-transition: width 350ms; + transition: width 350ms; + + background: #29d; + position: fixed; + z-index: 10002; + top: 0; + left: 0; + width: 100%; + height: 2px; + border-bottom-right-radius: 1px; + border-top-right-radius: 1px; +} + +/* Fancy blur effect */ +#loading-bar .peg { + position: absolute; + width: 70px; + right: 0; + top: 0; + height: 2px; + opacity: .45; + -moz-box-shadow: #29d 1px 0 6px 1px; + -ms-box-shadow: #29d 1px 0 6px 1px; + -webkit-box-shadow: #29d 1px 0 6px 1px; + box-shadow: #29d 1px 0 6px 1px; + -moz-border-radius: 100%; + -webkit-border-radius: 100%; + border-radius: 100%; +} + +#loading-bar-spinner { + display: block; + position: fixed; + z-index: 10002; + top: 10px; + left: 10px; +} + +#loading-bar-spinner .spinner-icon { + width: 14px; + height: 14px; + + border: solid 2px transparent; + border-top-color: #29d; + border-left-color: #29d; + border-radius: 50%; + + -webkit-animation: loading-bar-spinner 400ms linear infinite; + -moz-animation: loading-bar-spinner 400ms linear infinite; + -ms-animation: loading-bar-spinner 400ms linear infinite; + -o-animation: loading-bar-spinner 400ms linear infinite; + animation: loading-bar-spinner 400ms linear infinite; +} + +@-webkit-keyframes loading-bar-spinner { + 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } + 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } +} +@-moz-keyframes loading-bar-spinner { + 0% { -moz-transform: rotate(0deg); transform: rotate(0deg); } + 100% { -moz-transform: rotate(360deg); transform: rotate(360deg); } +} +@-o-keyframes loading-bar-spinner { + 0% { -o-transform: rotate(0deg); transform: rotate(0deg); } + 100% { -o-transform: rotate(360deg); transform: rotate(360deg); } +} +@-ms-keyframes loading-bar-spinner { + 0% { -ms-transform: rotate(0deg); transform: rotate(0deg); } + 100% { -ms-transform: rotate(360deg); transform: rotate(360deg); } +} +@keyframes loading-bar-spinner { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } +} diff --git a/src/main/resources/static/module/angular-loading-bar/loading-bar.js b/src/main/resources/static/module/angular-loading-bar/loading-bar.js new file mode 100644 index 0000000..01630c0 --- /dev/null +++ b/src/main/resources/static/module/angular-loading-bar/loading-bar.js @@ -0,0 +1,340 @@ +/*! + * angular-loading-bar v0.9.0 + * https://chieffancypants.github.io/angular-loading-bar + * Copyright (c) 2016 Wes Cruver + * License: MIT + */ +/* + * angular-loading-bar + * + * intercepts XHR requests and creates a loading bar. + * Based on the excellent nprogress work by rstacruz (more info in readme) + * + * (c) 2013 Wes Cruver + * License: MIT + */ + + +(function() { + +'use strict'; + +// Alias the loading bar for various backwards compatibilities since the project has matured: +angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']); +angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']); + + +/** + * loadingBarInterceptor service + * + * Registers itself as an Angular interceptor and listens for XHR requests. + */ +angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar']) + .config(['$httpProvider', function ($httpProvider) { + + var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) { + + /** + * The total number of requests made + */ + var reqsTotal = 0; + + /** + * The number of requests completed (either successfully or not) + */ + var reqsCompleted = 0; + + /** + * The amount of time spent fetching before showing the loading bar + */ + var latencyThreshold = cfpLoadingBar.latencyThreshold; + + /** + * $timeout handle for latencyThreshold + */ + var startTimeout; + + + /** + * calls cfpLoadingBar.complete() which removes the + * loading bar from the DOM. + */ + function setComplete() { + $timeout.cancel(startTimeout); + cfpLoadingBar.complete(); + reqsCompleted = 0; + reqsTotal = 0; + } + + /** + * Determine if the response has already been cached + * @param {Object} config the config option from the request + * @return {Boolean} retrns true if cached, otherwise false + */ + function isCached(config) { + var cache; + var defaultCache = $cacheFactory.get('$http'); + var defaults = $httpProvider.defaults; + + // Choose the proper cache source. Borrowed from angular: $http service + if ((config.cache || defaults.cache) && config.cache !== false && + (config.method === 'GET' || config.method === 'JSONP')) { + cache = angular.isObject(config.cache) ? config.cache + : angular.isObject(defaults.cache) ? defaults.cache + : defaultCache; + } + + var cached = cache !== undefined ? + cache.get(config.url) !== undefined : false; + + if (config.cached !== undefined && cached !== config.cached) { + return config.cached; + } + config.cached = cached; + return cached; + } + + + return { + 'request': function(config) { + // Check to make sure this request hasn't already been cached and that + // the requester didn't explicitly ask us to ignore this request: + if (!config.ignoreLoadingBar && !isCached(config)) { + $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url}); + if (reqsTotal === 0) { + startTimeout = $timeout(function() { + cfpLoadingBar.start(); + }, latencyThreshold); + } + reqsTotal++; + cfpLoadingBar.set(reqsCompleted / reqsTotal); + } + return config; + }, + + 'response': function(response) { + if (!response || !response.config) { + $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); + return response; + } + + if (!response.config.ignoreLoadingBar && !isCached(response.config)) { + reqsCompleted++; + if (reqsCompleted >= reqsTotal) { + $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response}); + setComplete(); + } else { + cfpLoadingBar.set(reqsCompleted / reqsTotal); + } + } + return response; + }, + + 'responseError': function(rejection) { + if (!rejection || !rejection.config) { + $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50'); + return $q.reject(rejection); + } + + if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) { + reqsCompleted++; + if (reqsCompleted >= reqsTotal) { + $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection}); + setComplete(); + } else { + cfpLoadingBar.set(reqsCompleted / reqsTotal); + } + } + return $q.reject(rejection); + } + }; + }]; + + $httpProvider.interceptors.push(interceptor); + }]); + + +/** + * Loading Bar + * + * This service handles adding and removing the actual element in the DOM. + * Generally, best practices for DOM manipulation is to take place in a + * directive, but because the element itself is injected in the DOM only upon + * XHR requests, and it's likely needed on every view, the best option is to + * use a service. + */ +angular.module('cfp.loadingBar', []) + .provider('cfpLoadingBar', function() { + + this.autoIncrement = true; + this.includeSpinner = true; + this.includeBar = true; + this.latencyThreshold = 100; + this.startSize = 0.02; + this.parentSelector = 'body'; + this.spinnerTemplate = '
'; + this.loadingBarTemplate = '
'; + + this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) { + var $animate; + var $parentSelector = this.parentSelector, + loadingBarContainer = angular.element(this.loadingBarTemplate), + loadingBar = loadingBarContainer.find('div').eq(0), + spinner = angular.element(this.spinnerTemplate); + + var incTimeout, + completeTimeout, + started = false, + status = 0; + + var autoIncrement = this.autoIncrement; + var includeSpinner = this.includeSpinner; + var includeBar = this.includeBar; + var startSize = this.startSize; + + /** + * Inserts the loading bar element into the dom, and sets it to 2% + */ + function _start() { + if (!$animate) { + $animate = $injector.get('$animate'); + } + + $timeout.cancel(completeTimeout); + + // do not continually broadcast the started event: + if (started) { + return; + } + + var document = $document[0]; + var parent = document.querySelector ? + document.querySelector($parentSelector) + : $document.find($parentSelector)[0] + ; + + if (! parent) { + parent = document.getElementsByTagName('body')[0]; + } + + var $parent = angular.element(parent); + var $after = parent.lastChild && angular.element(parent.lastChild); + + $rootScope.$broadcast('cfpLoadingBar:started'); + started = true; + + if (includeBar) { + $animate.enter(loadingBarContainer, $parent, $after); + } + + if (includeSpinner) { + $animate.enter(spinner, $parent, loadingBarContainer); + } + + _set(startSize); + } + + /** + * Set the loading bar's width to a certain percent. + * + * @param n any value between 0 and 1 + */ + function _set(n) { + if (!started) { + return; + } + var pct = (n * 100) + '%'; + loadingBar.css('width', pct); + status = n; + + // increment loadingbar to give the illusion that there is always + // progress but make sure to cancel the previous timeouts so we don't + // have multiple incs running at the same time. + if (autoIncrement) { + $timeout.cancel(incTimeout); + incTimeout = $timeout(function() { + _inc(); + }, 250); + } + } + + /** + * Increments the loading bar by a random amount + * but slows down as it progresses + */ + function _inc() { + if (_status() >= 1) { + return; + } + + var rnd = 0; + + // TODO: do this mathmatically instead of through conditions + + var stat = _status(); + if (stat >= 0 && stat < 0.25) { + // Start out between 3 - 6% increments + rnd = (Math.random() * (5 - 3 + 1) + 3) / 100; + } else if (stat >= 0.25 && stat < 0.65) { + // increment between 0 - 3% + rnd = (Math.random() * 3) / 100; + } else if (stat >= 0.65 && stat < 0.9) { + // increment between 0 - 2% + rnd = (Math.random() * 2) / 100; + } else if (stat >= 0.9 && stat < 0.99) { + // finally, increment it .5 % + rnd = 0.005; + } else { + // after 99%, don't increment: + rnd = 0; + } + + var pct = _status() + rnd; + _set(pct); + } + + function _status() { + return status; + } + + function _completeAnimation() { + status = 0; + started = false; + } + + function _complete() { + if (!$animate) { + $animate = $injector.get('$animate'); + } + + _set(1); + $timeout.cancel(completeTimeout); + + // Attempt to aggregate any start/complete calls within 500ms: + completeTimeout = $timeout(function() { + var promise = $animate.leave(loadingBarContainer, _completeAnimation); + if (promise && promise.then) { + promise.then(_completeAnimation); + } + $animate.leave(spinner); + $rootScope.$broadcast('cfpLoadingBar:completed'); + }, 500); + } + + return { + start : _start, + set : _set, + status : _status, + inc : _inc, + complete : _complete, + autoIncrement : this.autoIncrement, + includeSpinner : this.includeSpinner, + latencyThreshold : this.latencyThreshold, + parentSelector : this.parentSelector, + startSize : this.startSize + }; + + + }]; // + }); // wtf javascript. srsly +})(); // diff --git a/src/main/resources/static/module/angular-loading-bar/loading-bar.min.css b/src/main/resources/static/module/angular-loading-bar/loading-bar.min.css new file mode 100644 index 0000000..0f9f106 --- /dev/null +++ b/src/main/resources/static/module/angular-loading-bar/loading-bar.min.css @@ -0,0 +1 @@ +#loading-bar,#loading-bar-spinner{pointer-events:none;-webkit-pointer-events:none;-webkit-transition:350ms linear all;-moz-transition:350ms linear all;-o-transition:350ms linear all;transition:350ms linear all}#loading-bar-spinner.ng-enter,#loading-bar-spinner.ng-leave.ng-leave-active,#loading-bar.ng-enter,#loading-bar.ng-leave.ng-leave-active{opacity:0}#loading-bar-spinner.ng-enter.ng-enter-active,#loading-bar-spinner.ng-leave,#loading-bar.ng-enter.ng-enter-active,#loading-bar.ng-leave{opacity:1}#loading-bar .bar{-webkit-transition:width 350ms;-moz-transition:width 350ms;-o-transition:width 350ms;transition:width 350ms;background:#29d;position:fixed;z-index:10002;top:0;left:0;width:100%;height:2px;border-bottom-right-radius:1px;border-top-right-radius:1px}#loading-bar .peg{position:absolute;width:70px;right:0;top:0;height:2px;opacity:.45;-moz-box-shadow:#29d 1px 0 6px 1px;-ms-box-shadow:#29d 1px 0 6px 1px;-webkit-box-shadow:#29d 1px 0 6px 1px;box-shadow:#29d 1px 0 6px 1px;-moz-border-radius:100%;-webkit-border-radius:100%;border-radius:100%}#loading-bar-spinner{display:block;position:fixed;z-index:10002;top:10px;left:10px}#loading-bar-spinner .spinner-icon{width:14px;height:14px;border:2px solid transparent;border-top-color:#29d;border-left-color:#29d;border-radius:50%;-webkit-animation:loading-bar-spinner 400ms linear infinite;-moz-animation:loading-bar-spinner 400ms linear infinite;-ms-animation:loading-bar-spinner 400ms linear infinite;-o-animation:loading-bar-spinner 400ms linear infinite;animation:loading-bar-spinner 400ms linear infinite}@-webkit-keyframes loading-bar-spinner{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-moz-keyframes loading-bar-spinner{0%{-moz-transform:rotate(0);transform:rotate(0)}100%{-moz-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes loading-bar-spinner{0%{-o-transform:rotate(0);transform:rotate(0)}100%{-o-transform:rotate(360deg);transform:rotate(360deg)}}@-ms-keyframes loading-bar-spinner{0%{-ms-transform:rotate(0);transform:rotate(0)}100%{-ms-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes loading-bar-spinner{0%{transform:rotate(0)}100%{transform:rotate(360deg)}} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-loading-bar/loading-bar.min.js b/src/main/resources/static/module/angular-loading-bar/loading-bar.min.js new file mode 100644 index 0000000..e4b18ad --- /dev/null +++ b/src/main/resources/static/module/angular-loading-bar/loading-bar.min.js @@ -0,0 +1,7 @@ +/*! + * angular-loading-bar v0.9.0 + * https://chieffancypants.github.io/angular-loading-bar + * Copyright (c) 2016 Wes Cruver + * License: MIT + */ +!function(){"use strict";angular.module("angular-loading-bar",["cfp.loadingBarInterceptor"]),angular.module("chieffancypants.loadingBar",["cfp.loadingBarInterceptor"]),angular.module("cfp.loadingBarInterceptor",["cfp.loadingBar"]).config(["$httpProvider",function(a){var b=["$q","$cacheFactory","$timeout","$rootScope","$log","cfpLoadingBar",function(b,c,d,e,f,g){function h(){d.cancel(j),g.complete(),l=0,k=0}function i(b){var d,e=c.get("$http"),f=a.defaults;!b.cache&&!f.cache||b.cache===!1||"GET"!==b.method&&"JSONP"!==b.method||(d=angular.isObject(b.cache)?b.cache:angular.isObject(f.cache)?f.cache:e);var g=void 0!==d?void 0!==d.get(b.url):!1;return void 0!==b.cached&&g!==b.cached?b.cached:(b.cached=g,g)}var j,k=0,l=0,m=g.latencyThreshold;return{request:function(a){return a.ignoreLoadingBar||i(a)||(e.$broadcast("cfpLoadingBar:loading",{url:a.url}),0===k&&(j=d(function(){g.start()},m)),k++,g.set(l/k)),a},response:function(a){return a&&a.config?(a.config.ignoreLoadingBar||i(a.config)||(l++,l>=k?(e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url,result:a}),h()):g.set(l/k)),a):(f.error("Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"),a)},responseError:function(a){return a&&a.config?(a.config.ignoreLoadingBar||i(a.config)||(l++,l>=k?(e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url,result:a}),h()):g.set(l/k)),b.reject(a)):(f.error("Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"),b.reject(a))}}}];a.interceptors.push(b)}]),angular.module("cfp.loadingBar",[]).provider("cfpLoadingBar",function(){this.autoIncrement=!0,this.includeSpinner=!0,this.includeBar=!0,this.latencyThreshold=100,this.startSize=.02,this.parentSelector="body",this.spinnerTemplate='
',this.loadingBarTemplate='
',this.$get=["$injector","$document","$timeout","$rootScope",function(a,b,c,d){function e(){if(k||(k=a.get("$animate")),c.cancel(m),!r){var e=b[0],g=e.querySelector?e.querySelector(n):b.find(n)[0];g||(g=e.getElementsByTagName("body")[0]);var h=angular.element(g),i=g.lastChild&&angular.element(g.lastChild);d.$broadcast("cfpLoadingBar:started"),r=!0,v&&k.enter(o,h,i),u&&k.enter(q,h,o),f(w)}}function f(a){if(r){var b=100*a+"%";p.css("width",b),s=a,t&&(c.cancel(l),l=c(function(){g()},250))}}function g(){if(!(h()>=1)){var a=0,b=h();a=b>=0&&.25>b?(3*Math.random()+3)/100:b>=.25&&.65>b?3*Math.random()/100:b>=.65&&.9>b?2*Math.random()/100:b>=.9&&.99>b?.005:0;var c=h()+a;f(c)}}function h(){return s}function i(){s=0,r=!1}function j(){k||(k=a.get("$animate")),f(1),c.cancel(m),m=c(function(){var a=k.leave(o,i);a&&a.then&&a.then(i),k.leave(q),d.$broadcast("cfpLoadingBar:completed")},500)}var k,l,m,n=this.parentSelector,o=angular.element(this.loadingBarTemplate),p=o.find("div").eq(0),q=angular.element(this.spinnerTemplate),r=!1,s=0,t=this.autoIncrement,u=this.includeSpinner,v=this.includeBar,w=this.startSize;return{start:e,set:f,status:h,inc:g,complete:j,autoIncrement:this.autoIncrement,includeSpinner:this.includeSpinner,latencyThreshold:this.latencyThreshold,parentSelector:this.parentSelector,startSize:this.startSize}}]})}(); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-meditor/meditor.css b/src/main/resources/static/module/angular-meditor/meditor.css new file mode 100644 index 0000000..e2a39fe --- /dev/null +++ b/src/main/resources/static/module/angular-meditor/meditor.css @@ -0,0 +1,107 @@ +/* Meditor + */ +/* Bourbon + */ +/* Utils + */ +/* Utils +*/ +/* Mixins */ +.angular-meditor { + position: relative; } + +.angular-meditor-toolbar { + position: absolute; + z-index: -1; + display: block; + border: 1px solid #1d1d1d; + border-radius: 3px; + opacity: 0; + padding: 0; + font-size: 16px; + -webkit-transition-property: -webkit-transform, opacity; + -moz-transition-property: -moz-transform, opacity; + transition-property: transform, opacity; + -webkit-transition-duration: 0.075s; + -moz-transition-duration: 0.075s; + transition-duration: 0.075s; + -webkit-transition-timing-function: ease-out; + -moz-transition-timing-function: ease-out; + transition-timing-function: ease-out; + -webkit-transform: translate3d(0, 10px, 0); + -moz-transform: translate3d(0, 10px, 0); + -ms-transform: translate3d(0, 10px, 0); + -o-transform: translate3d(0, 10px, 0); + transform: translate3d(0, 10px, 0); } + .angular-meditor-toolbar:after { + position: absolute; + bottom: -0.4375em; + left: 50%; + margin-left: -0.1875em; + content: ''; + display: block; + width: 0; + height: 0; + border-width: 0.4375em 0.4375em 0; + border-style: solid; + border-color: #1d1d1d transparent transparent; } + .angular-meditor-toolbar.angular-meditor-toolbar--bottom:after { + bottom: auto; + top: -0.4375em; + border-width: 0 0.4375em 0.4375em; + border-color: transparent transparent #1d1d1d; } + .angular-meditor-toolbar ul { + overflow: hidden; + display: table-row; + list-style-type: none; + border-radius: 3px; } + .angular-meditor-toolbar li { + display: table-cell; + border: 0; + padding: 0; + margin: 0; } + .angular-meditor-toolbar button, .angular-meditor-toolbar select { + float: left; + height: 2.25em; + margin: 0; + padding: 0.5em 0.75em; + background-color: #222; + border-width: 1px 0 0 0; + border-color: #2f2f2f; + border-style: solid; + box-shadow: none; + font-size: 1em; + color: #efefef; + -webkit-transition: all .1s; + -moz-transition: all .1s; + transition: all .1s; } + .angular-meditor-toolbar button:hover, .angular-meditor-toolbar select:hover { + cursor: pointer; + background-color: #151515; } + .angular-meditor-toolbar select { + overflow: hidden; + width: 4em; + text-overflow: ellipsis; } + .angular-meditor-toolbar .meditor-family-selector { + width: 7.5em; } + .angular-meditor-toolbar button { + width: 2.5em; } + .angular-meditor-toolbar .meditor-button--active { + background-color: #151515; + border-width: 0 0 1px 0; } + .angular-meditor-toolbar .meditor-select { + position: relative; + overflow: hidden; + min-width: 3.25em; + margin: 0; + padding: 0; + font-size: 1em; } + +.angular-meditor-toolbar--show { + opacity: 1; + z-index: 999999; + -webkit-transform: translate3d(0, 0, 0); + -moz-transform: translate3d(0, 0, 0); + -ms-transform: translate3d(0, 0, 0); + -o-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); } diff --git a/src/main/resources/static/module/angular-meditor/meditor.js b/src/main/resources/static/module/angular-meditor/meditor.js new file mode 100644 index 0000000..2f75a53 --- /dev/null +++ b/src/main/resources/static/module/angular-meditor/meditor.js @@ -0,0 +1,411 @@ +/* angular-meditor directive + */ + +angular.module('angular-meditor', []) +.directive('meditor', [ '$timeout', function ($timeout) { + 'use strict'; + + return { + scope: { + ngModel: '=', + toolbarContainer: '@?' + }, + require: '?ngModel', + transclude: true, + templateUrl: 'views/editor.html', + link: function (scope, element, attributes, ctrl) { + + scope.model = { + ngModel: scope.ngModel, + showToolbar: false + }; + + scope.$watch('model.ngModel', function() { + $timeout(function(){ + scope.ngModel = scope.model.ngModel; + }); + }); + + // toolbar position + scope.position = { + top: 10, + left: 10, + below: false + }; + + // fontSize options + scope.sizeOptions = [ + { + label: '10', + value: 1 + }, + { + label: '13', + value: 2 + }, + { + label: '16', + value: 3 + }, + { + label: '18', + value: 4 + }, + { + label: '24', + value: 5 + }, + { + label: '32', + value: 6 + }, + { + label: '48', + value: 7 + } + ]; + scope.size = scope.sizeOptions[0].value; + + scope.familyOptions = [ + { + label: 'Open Sans', + value: 'Open Sans, sans-serif' + }, + { + label: 'Source Sans Pro', + value: 'Source Sans Pro, sans-serif' + }, + { + label: 'Exo', + value: 'Exo, sans-serif' + }, + { + label: 'Oswald', + value: 'Oswald, sans-serif' + }, + { + label: 'Cardo', + value: 'Cardo, serif' + }, + { + label: 'Vollkorn', + value: 'Vollkorn, serif' + }, + { + label: 'Old Standard TT', + value: 'Old Standard TT, serif' + } + ]; + scope.family = scope.familyOptions[0]; + + // current styles of selected elements + // used to highlight active buttons + scope.styles = {}; + + // tags generated by the editor + // used to highlight active styles + var generatedTags = { + 'b': '', + 'strong': '', + 'i': '', + 'em': '', + 'u': '' + }; + + // Remy Sharp's debounce + // https://remysharp.com/2010/07/21/throttling-function-calls + var debounce = function(fn, delay) { + var timer = null; + return function () { + var context = this, args = arguments; + clearTimeout(timer); + timer = setTimeout(function () { + fn.apply(context, args); + }, delay); + }; + }; + + var $toolbar = angular.element(element[0].querySelector('.angular-meditor-toolbar')); + var $content = angular.element(element[0].querySelector('.angular-meditor-content')); + var $selects = angular.element(element[0].querySelector('select')); + var $body = angular.element(document.querySelector(scope.toolbarContainer) || document.body); + + // position the toolbar above or below the selected text + var setToolbarPosition = function () { + var toolbarHeight = $toolbar[0].offsetHeight; + var toolbarWidth = $toolbar[0].offsetWidth; + var spacing = 5; + var selection = window.getSelection(); + var range = selection.getRangeAt(0); + var boundary = range.getBoundingClientRect(); + + var topPosition = boundary.top; + var leftPosition = boundary.left; + + // if there isn't enough space at the top, place it at the bottom + // of the selection + if(boundary.top < (toolbarHeight + spacing)) { + scope.position.top = topPosition + boundary.height + spacing; + // tell me if it's above or below the selection + // used in the template to place the triangle above or below + scope.position.below = true; + } else { + scope.position.top = topPosition - toolbarHeight - spacing; + scope.position.below = false; + } + + // center toolbar above selected text + scope.position.left = leftPosition - (toolbarWidth/2) + (boundary.width/2); + + // cross-browser window scroll positions + var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft; + var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; + + // add the scroll positions + // because getBoundingClientRect gives us the position + // relative to the viewport, not to the page + scope.position.top += scrollTop; + scope.position.left += scrollLeft; + + return this; + }; + + // get current selection and act on toolbar depending on it + var checkSelection = function (e) { + + // if you click something from the toolbar + // don't do anything + if(e && e.target && $toolbar.find(e.target).length) { + return false; + } + + var newSelection = window.getSelection(); + + // get selection node + var anchorNode = newSelection.anchorNode; + + // if nothing selected, hide the toolbar + if(newSelection.toString().trim() === '' || !anchorNode) { + // hide the toolbar + return $timeout(function() { + scope.model.showToolbar = false; + }); + } + + // check if selection is in the current editor/directive container + var parentNode = anchorNode.parentNode; + while (parentNode.tagName !== undefined && parentNode !== element[0]) { + parentNode = parentNode.parentNode; + } + + // if the selection is in the current editor + if(parentNode === element[0]) { + // show the toolbar + $timeout(function() { + scope.model.showToolbar = true; + setToolbarPosition(); + }); + + // check selection styles and active buttons based on it + checkActiveButtons(newSelection); + } else { + // hide the toolbar + $timeout(function() { + scope.model.showToolbar = false; + }); + } + + return this; + }; + + // check current selection styles and activate buttons + var checkActiveButtons = function (selection) { + var parentNode = selection.anchorNode; + + if (!parentNode.tagName) { + parentNode = selection.anchorNode.parentNode; + } + + var childNode = parentNode.childNodes[0]; + + if(childNode && childNode.tagName && childNode.tagName.toLowerCase() in generatedTags) { + parentNode = parentNode.childNodes[0]; + } + + $timeout(function() { + // get real styles of selected element + scope.styles = window.getComputedStyle(parentNode, null); + + if(scope.styles.fontSize !== scope.size.label + 'px') { + // set font size selector + angular.forEach(scope.sizeOptions, function(size, i) { + if(scope.styles.fontSize === (size.label + 'px')) { + scope.size = scope.sizeOptions[i].value; + return false; + } + }); + } + + }); + + }; + + // check selection when selecting with the shift key + $content.bind('keyup', checkSelection); + + // check the selection on every mouseup + // it also triggeres when releasing outside the browser + + // use debounce to fix issue with Chrome + // getting the right selection only after a delay + // if selecting text, then single-clicking the selected text + document.addEventListener('mouseup', debounce(checkSelection, 200)); + + $content.bind('blur', debounce(checkSelection, 200)); + + // if after a selection in the select, + // the contenteditable doesn't get the focus + // the toolbar will not hide on blur. + // so I have to add a blur event to the selects. + $selects.bind('blur', debounce(checkSelection, 200)); + + // simple edit action - bold, italic, underline + scope.SimpleAction = function(action) { + document.execCommand('styleWithCSS', false, false); + document.execCommand(action, false, null); + + // custom event for two-way binding + scope.$broadcast('meditor-change'); + }; + + // watch the font size selector + scope.$watch('size', function() { + document.execCommand('styleWithCSS', false, false); + document.execCommand('fontSize', false, scope.size); + + // custom event for two-way binding + scope.$broadcast('meditor-change'); + }); + + // watch the font family selector + scope.$watch('family', function() { + // dynamically load the family from google fonts + if(window.WebFont) { + WebFont.load({ + google: { + families: [ scope.family.label ] + } + }); + } + + document.execCommand('styleWithCSS', false, true); + document.execCommand('fontName', false, scope.family.value); + + // custom event for two-way binding + scope.$broadcast('meditor-change'); + }); + + // load google webfont library + // to be able to dynamically load fonts + (function() { + var wf = document.createElement('script'); + wf.src = ('https:' === document.location.protocol ? 'https' : 'http') + + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; + wf.type = 'text/javascript'; + wf.async = 'true'; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(wf, s); + })(); + + // move the toolbar to the body, we can use overflow: hidden on containers + $body.append($toolbar); + + } + }; + +}]) +.directive('meditorContenteditable', [ '$timeout', function($timeout) { + 'use strict'; + + return { + require: '?ngModel', + link: function(scope, elm, attrs, ctrl) { + + // don't throw an error without ng-model + if(typeof scope.ngModel !== 'undefined') { + + var change = function() { + $timeout(function() { + ctrl.$setViewValue(elm.html()); + }); + }; + + // custom event to change the ngModel after using + // actions from the editor + scope.$on('meditor-change', change); + + elm.on('blur keyup', change); + + ctrl.$render = function() { + elm.html(ctrl.$viewValue); + }; + + ctrl.$setViewValue(scope.ngModel); + elm.html(ctrl.$viewValue); + + scope.$watch('ngModel', function(ngModel) { + // change the html only if it's different from the model + // eg. on outside changes + // so we don't lose the selection when editing with the + // editor toolbar + if(elm.html() !== ngModel) { + elm.html(ngModel); + } + }); + + } + + } + }; +}]); + +angular.module('angular-meditor').run(['$templateCache', function($templateCache) { + 'use strict'; + + $templateCache.put('views/editor.html', + "
\n" + + "
\n" + + "
    \n" + + "
  • \n" + + " \n" + + "
  • \n" + + "
  • \n" + + " \n" + + "
  • \n" + + "
  • \n" + + " \n" + + "
  • \n" + + "
  • \n" + + " \n" + + "
  • \n" + + "
  • \n" + + " \n" + + "
  • \n" + + "
\n" + + "
\n" + + "\n" + + "
\n" + + "
\n" + ); + +}]); diff --git a/src/main/resources/static/module/angular-meditor/meditor.min.css b/src/main/resources/static/module/angular-meditor/meditor.min.css new file mode 100644 index 0000000..d4ce103 --- /dev/null +++ b/src/main/resources/static/module/angular-meditor/meditor.min.css @@ -0,0 +1 @@ +.angular-meditor{position:relative}.angular-meditor-toolbar{position:absolute;z-index:-1;display:block;border:1px solid #1d1d1d;border-radius:3px;opacity:0;padding:0;font-size:16px;-webkit-transition-property:-webkit-transform,opacity;-moz-transition-property:-moz-transform,opacity;transition-property:transform,opacity;-webkit-transition-duration:.075s;-moz-transition-duration:.075s;transition-duration:.075s;-webkit-transition-timing-function:ease-out;-moz-transition-timing-function:ease-out;transition-timing-function:ease-out;-webkit-transform:translate3d(0,10px,0);-moz-transform:translate3d(0,10px,0);-ms-transform:translate3d(0,10px,0);-o-transform:translate3d(0,10px,0);transform:translate3d(0,10px,0)}.angular-meditor-toolbar:after{position:absolute;bottom:-.4375em;left:50%;margin-left:-.1875em;content:'';display:block;width:0;height:0;border-width:.4375em .4375em 0;border-style:solid;border-color:#1d1d1d transparent transparent}.angular-meditor-toolbar.angular-meditor-toolbar--bottom:after{bottom:auto;top:-.4375em;border-width:0 .4375em .4375em;border-color:transparent transparent #1d1d1d}.angular-meditor-toolbar ul{overflow:hidden;display:table-row;list-style-type:none;border-radius:3px}.angular-meditor-toolbar li{display:table-cell;border:0;padding:0;margin:0}.angular-meditor-toolbar button,.angular-meditor-toolbar select{float:left;height:2.25em;margin:0;padding:.5em .75em;background-color:#222;border-width:1px 0 0;border-color:#2f2f2f;border-style:solid;box-shadow:none;font-size:1em;color:#efefef;-webkit-transition:all .1s;-moz-transition:all .1s;transition:all .1s}.angular-meditor-toolbar button:hover,.angular-meditor-toolbar select:hover{cursor:pointer;background-color:#151515}.angular-meditor-toolbar select{overflow:hidden;width:4em;text-overflow:ellipsis}.angular-meditor-toolbar .meditor-family-selector{width:7.5em}.angular-meditor-toolbar button{width:2.5em}.angular-meditor-toolbar .meditor-button--active{background-color:#151515;border-width:0 0 1px}.angular-meditor-toolbar .meditor-select{position:relative;overflow:hidden;min-width:3.25em;margin:0;padding:0;font-size:1em}.angular-meditor-toolbar--show{opacity:1;z-index:999999;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-meditor/meditor.min.js b/src/main/resources/static/module/angular-meditor/meditor.min.js new file mode 100644 index 0000000..521ab60 --- /dev/null +++ b/src/main/resources/static/module/angular-meditor/meditor.min.js @@ -0,0 +1 @@ +angular.module("angular-meditor",[]).directive("meditor",["$timeout",function(a){"use strict";return{scope:{ngModel:"=",toolbarContainer:"@?"},require:"?ngModel",transclude:!0,templateUrl:"views/editor.html",link:function(b,c,d,e){b.model={ngModel:b.ngModel,showToolbar:!1},b.$watch("model.ngModel",function(){a(function(){b.ngModel=b.model.ngModel})}),b.position={top:10,left:10,below:!1},b.sizeOptions=[{label:"10",value:1},{label:"13",value:2},{label:"16",value:3},{label:"18",value:4},{label:"24",value:5},{label:"32",value:6},{label:"48",value:7}],b.size=b.sizeOptions[0].value,b.familyOptions=[{label:"Open Sans",value:"Open Sans, sans-serif"},{label:"Source Sans Pro",value:"Source Sans Pro, sans-serif"},{label:"Exo",value:"Exo, sans-serif"},{label:"Oswald",value:"Oswald, sans-serif"},{label:"Cardo",value:"Cardo, serif"},{label:"Vollkorn",value:"Vollkorn, serif"},{label:"Old Standard TT",value:"Old Standard TT, serif"}],b.family=b.familyOptions[0],b.styles={};var f={b:"",strong:"",i:"",em:"",u:""},g=function(a,b){var c=null;return function(){var d=this,e=arguments;clearTimeout(c),c=setTimeout(function(){a.apply(d,e)},b)}},h=angular.element(c[0].querySelector(".angular-meditor-toolbar")),i=angular.element(c[0].querySelector(".angular-meditor-content")),j=angular.element(c[0].querySelector("select")),k=angular.element(document.querySelector(b.toolbarContainer)||document.body),l=function(){var a=h[0].offsetHeight,c=h[0].offsetWidth,d=5,e=window.getSelection(),f=e.getRangeAt(0),g=f.getBoundingClientRect(),i=g.top,j=g.left;g.top\n
\n
    \n
  • \n \n
  • \n
  • \n \n
  • \n
  • \n \n
  • \n
  • \n \n
  • \n
  • \n \n
  • \n
\n
\n\n
\n\n')}]); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-multirange/multirange.css b/src/main/resources/static/module/angular-multirange/multirange.css new file mode 100644 index 0000000..d1f4d6f --- /dev/null +++ b/src/main/resources/static/module/angular-multirange/multirange.css @@ -0,0 +1,192 @@ +/* + * multirange.js v0.1.4 + * (c) 2015 Ahmad Ali, ahmadalibaloch@gmail.com + * License: MIT + */ + +.vds-multirange-mk2-container { + position: relative; + width: 100%; + height: 110px; + overflow-x: auto; + overflow-y: hidden; +} + +.vds-multirange-mk2-labels-container { + margin-left: 5px; +} + +.vds-multirange-mk2-labels { + position: relative; + width: 100%; + height: 35px; + padding: 0; + margin: 2px auto; + list-style: none; +} + +.vds-multirange-mk2-label { + position: absolute; + bottom: 0px; +} + +.vds-multirange-mk2-label span { + display: inline-block; + margin-left: -50%; + font-size: 11px; + color: #fff; + font-family: 'Arial', sans-serif; + text-align: center; + background-color: rgba(0,0,0,0.75); + border: none; + border-radius: 8px; + padding: 4px 6px; +} +.vds-multirange-mk2-label input[type="text"] { + display: inline-block; + margin-left: -50%; + font-size: 11px; + color: #4C4040; + font-family: 'Arial', sans-serif; + text-align: center; + background-color: rgba(227, 237, 230, 0.17); + border: 1px solid; + border-radius: 8px; + padding: 2px 6px; + width:44px; +} + +.vds-multirange-mk2-hairline { + position: absolute; + border-left: 1px solid black; +} + +.vds-multirange-mk2-hairlines-container { + margin-left: 5px; +} + +.vds-multirange-mk2-hairlines { + position: relative; + width: 100%; + height: 25px; + padding: 0; + margin: auto; + list-style: none; +} + +.vds-multirange-mk2-hairline { + position: absolute; + border-left: 1px solid rgba(0,0,0,0.6); +} + +.vds-multirange-mk2-hairline span { + display: inline-block; + margin-left: -50%; + margin-top: 14px; + font-size: 11px; + color: rgba(0,0,0,0.6); + font-family: 'Arial', sans-serif; +} + +.vds-multirange-container { + position: relative; + width: 100%; + height: 20px; + /* DO NOT MODIFY MARGIN */ +} + +.vds-multirange-wrapper { + position: absolute; + top: 0; + left: 0; + right: 0; +} + +.vds-multirange-track { + position: absolute; + top: 8px; + left: 0; + right: 0; + width: 100%; + height: 4px; + border-radius: 4px; + background-color: rgba(210,210,210,0.8); +} + +.vds-multirange { + -webkit-appearance: none; + width: 100%; + margin: 1px 0 0 0; + padding: 0; + cursor: pointer; + box-shadow:none; +} + +.vds-multirange:focus { + outline: none; +} + +/*http://stackoverflow.com/questions/18794026/remove-dotted-outline-from-range-input-element-in-firefox*/ +.vds-multirange::-moz-focus-outer { + border: 0; +} + +.vds-multirange::-webkit-slider-thumb { + -webkit-appearance: none; + border: none; + height: 20px; + width: 10px; + border-radius: 0 0 5px 5px; + background: rgba(66,139,202,0.75); +} + +.vds-multirange::-webkit-slider-runnable-track { + height: 1px; + border: none; + background: transparent; + margin-top: -1px; +} + +.vds-multirange::-moz-range-thumb { + border: none; + height: 20px; + width: 10px; + border-radius: 4px; + background: rgba(66,139,202,0.75); +} + +.vds-multirange::-moz-range-track { + height: 1px; + border: none; + background: transparent; + margin-top: -1px; +} + +.vds-multirange::-ms-tooltip { + display: none; +} + +.vds-multirange::-ms-thumb { + border: none; + height: 20px; + width: 10px; + border-radius: 4px; + background: rgba(66,139,202,0.75); +} + +.vds-multirange::-ms-track { + background: transparent; + color: transparent; + border-color: transparent; + border-width: 6px 0; +} + +.vds-multirange::-ms-fill-lower { + height: 1px; + background-color: transparent; +} + +.vds-multirange::-ms-fill-upper { + height: 1px; + background-color: transparent; +} diff --git a/src/main/resources/static/module/angular-multirange/multirange.js b/src/main/resources/static/module/angular-multirange/multirange.js new file mode 100644 index 0000000..431558d --- /dev/null +++ b/src/main/resources/static/module/angular-multirange/multirange.js @@ -0,0 +1,442 @@ +/* + * multirange.js v0.1.4 + * (c) 2015 Ahmad Ali, ahmadalibaloch@gmail.com + * License: MIT + */ + +'use strict'; + +angular.module('vds.multirange', ['vds.multirange.lite', 'vds.utils']) + .directive('vdsMultirange', function (vdsMultirangeViews) { + return { + required: 'ngModel', + scope: { + ngModel: '=', + _views: '=views', + _view: '=view', + gradient:'=', + ngDisabled: '=' + }, + template: + '
' + + '' + + '' + + '' + + '
', + link: function (scope, elem, attr) { + scope.getPercent = function(value) { + return (value*100) + '%'; + }; + + scope.changeView = function (n) { + if(typeof n == 'undefined' || typeof scope.views == 'undefined') return; + var l = scope.views.length-1, view; + n = (n < 0)? 0 : ( (n > l)? l : n ); + view = scope.views[n]; + if(typeof view != 'undefined') { + scope.zoom = view.zoom; + scope.step = view.step; + scope.units = view.units; + scope.renderer(); + } + }; + + scope.$watch('_view', function (n) { + scope.changeView(n); + }); + + scope.$watch('_views', function (n) { + scope.views = n; + scope.view = 0; + scope.changeView(0); + }); + + scope.renderer = function () { + if(typeof scope.zoom == 'undefined') return; + var render = { + container: {}, + content: {}, + multirange: { + width: scope.getPercent(scope.zoom), + display: 'block', + margin: 'auto' + } + }; + + if(scope.zoom < 1) { + render.content.margin = '2 auto'; + render.content.width = 'calc('+scope.getPercent(scope.zoom)+' - 10px)'; + render.container.marginLeft = '0'; + } else { + render.content.margin = '2 0'; + render.content.width = 'calc('+scope.getPercent(scope.zoom)+' - '+ ( 10 - ( scope.zoom * 5 ) ) +'px)'; + render.container.marginLeft = '5px'; + } + return scope.renderedStyle = render; + }; + + // set default view config + if(typeof scope.views == 'undefined') { + scope.views = vdsMultirangeViews.DEFAULT; + scope.view = 0; + scope.changeView(0); + } + + } + }; + }) + .directive('vdsMultirangeLabels', function (vdsUtils) { + return { + restrict: 'E', + scope: { + ngModel: '=', + render: '=', + ngDisabled: '=' + }, + template: + '
' + + '
    ' + + '
  • ' + + '{{ getName(range) }}' + + '' + + '
  • ' + + '
' + + '
', + link: function (scope, elem, attr) { + scope.lblDblClick = function(range){ + range.editing = true; + range.backupText=scope.getName(range); + }; + + scope.done = function($event,range){ + if ($event.which === 13){ + scope.applyTime(range); + } + }; + + scope.applyTime = function(range){ + if(range.backupText.length == 0) + return; + range.value = vdsUtils.time.fromTimeStringToValue(range.backupText); + range.editing=false; + } + + scope.getName = function(range){ + if (range.name) + return range.name; + return vdsUtils.time.fromValueToTime(range.value).label; + }; + + scope.renderRange = function (range) { + return { + left: (range.value*100)+'%', + zIndex: range._depth + } + }; + } + } + }) + .directive('vdsMultirangeHairlines', function () { + return { + restrict: 'E', + scope: { + ngModel: '=', + render: '=', + ngDisabled: '=' + }, + template: + '
'+ + '
    ' + + '
  • ' + + '{{ hairline.label }}' + + '
  • ' + + '
' + + '
', + link: function (scope, elem, attr) { + + scope.$watch('ngModel', function (n) { + if(typeof n == 'undefined') return; + scope.hairlines = []; + var levels = n.length, hairHeight = 12, hairline, i, j, u; + for(i = 0; i < levels; i++) { + u = n[i]; + for( j = 0; ((j>1)? Math.round(j*1000)/1000 : j) <= 1; j = parseFloat((j + u.value).toFixed(8)) ) { + hairline = { + render: { + height: hairHeight * (1 - i / levels), + left: (j*100)+'%' + } + } + if(typeof u.labeller == 'function') { + hairline.label = u.labeller(j); + } else if(typeof u.labeller != 'undefined') { + hairline.label = j; + } + scope.hairlines.push(hairline); + } + } + }); + + } + }; + }) + .factory('vdsMultirangeViews', function (vdsUtils) { + var tv = vdsUtils.time.fromTimeToValue, + vt = vdsUtils.time.fromValueToTime, + pad = vdsUtils.format.padZeroes, + toLabel = function(n){ + var hour = vt(n).hours; + return hour == 0 | hour == 24 ? '' : hour; + }; + return { + TIME: [ + { zoom: 0.9, step: tv(0,15), units: [ + { value: tv(1,0), labeller: function (n) { return toLabel(n) } }, + { value: tv(0,30) } + ] }, + { zoom: 1.2, step: tv(0,10), units: [ + { value: tv(1,0), labeller: function (n) { return vt(n).hours+'h' } }, + { value: tv(0,30) } + ] }, + { zoom: 1.4, step: tv(0,6), units: [ + { value: tv(1,0), labeller: function (n) { return vt(n).hours+'h' } }, + { value: tv(0,30) }, + { value: tv(0,12) } + ] }, + { zoom: 3.4, step: tv(0,1), units: [ + { value: tv(1,0) }, + { value: tv(0,15), labeller: function (n) { + var h = vt(n).hours, m = vt(n).minutes; + return (m==0)? h+'h' : h+':'+pad(m,2); + } }, + { value: tv(0,5) } + ] } + ], + DEFAULT: [ + { zoom: 0.9, step: 1/40, units: [ { value: 1/10, labeller: function (n) { return n*10 } }, { value: 1/20, } ] }, + { zoom: 1.5, step: 1/80, units: [ { value: 1/20, labeller: function (n) { return n*10 } }, { value: 1/40, } ] } + ] + } + }); + +angular.module('vds.multirange.lite', []) + .directive('vdsMultirangeLite', function (vdsUtils) { + return { + required: 'ngModel', + scope: { + ngModel: '=', + step: '=', + gradient:'=', + ngDisabled: '=' + }, + template: + '
' + + '
' + + '
' + + '' + + '
' + + '
', + link: function (scope, elem, attr) { + var mousex; + scope.precision = 1000000; + scope.preciseStep = 1; + scope.onMouseMove = function (evt) { + var bound = elem[0].getBoundingClientRect(); + mousex = (evt.pageX - bound.left) / bound.width; + }; + scope.computeDepth = function (range) { + var depth = 100 - Math.round(Math.abs(mousex-range.value)*100); + range._depth = depth >=0 ? depth : 0; + return { + zIndex: range._depth + }; + }; + scope.$watch('step', function () { + if(typeof scope.step == 'undefined') { + scope.preciseStep = 1; + } else { + scope.preciseStep = scope.step * scope.precision; + } + }); + //Multi-Color + //Sort by value + scope.ngModel.sort( + function(a,b) + { + if(a.valueb.value)return 1; + return 0; + }); + + //=========================================== + var defaultColor = "rgb(255, 0, 0)"; + // + scope.ngModel.map(function(el){if(!el.color || el.color=="undefined" || el.color.length < 3)el.color=defaultColor;}); + scope.$watch('ngModel',function(nv,ov){ + if(nv==ov)return; + // Control the sliders positions + var thisSliderVal; + var nextSliderVal; + var prevSliderVal; + var colorString = ""; + var sCount = scope.ngModel.length; + var getValue = function(range){ + if (range.value) + return range.value; + if (range.time) + return vdsUtils.time.fromTimeStringToValue(range.time); + if (range.hour) + return vdsUtils.time.fromTimeToValue(range.hour, range.minutes); + }; + + for(var i=0;i 0){//not last or first + nextSliderVal = scope.ngModel[i+1].value; + prevSliderVal = scope.ngModel[i-1].value; + + if(thisSliderVal >= nextSliderVal){ + scope.ngModel[i].value=nextSliderVal; + } + if(thisSliderVal <= prevSliderVal){ + scope.ngModel[i].value=prevSliderVal; + } + //color + if(scope.gradient){ + colorString +=scope.ngModel[i].color+" "+scope.ngModel[i].value*100+"%,"; + } + else{ + colorString += scope.ngModel[i].color+" "+scope.ngModel[i-1].value*100+"%,"+scope.ngModel[i].color+" "+scope.ngModel[i].value*100+"%,"; + } + } + else if(i==0){//first + nextSliderVal = scope.ngModel[i+1].value; + + if(thisSliderVal >= nextSliderVal){ + scope.ngModel[i].value=nextSliderVal; + } + if(thisSliderVal <= 0){ + scope.ngModel[i].value=0; + } + //color + if(scope.gradient){ + colorString +=scope.ngModel[i].color+" "+scope.ngModel[i].value*100+"%,"; + } + else{ + colorString += scope.ngModel[i].color+" 0%,"+scope.ngModel[i].color+" "+scope.ngModel[i].value*100+"%,"; + } + } + else if(i==sCount-1){//last + prevSliderVal = scope.ngModel[i-1].value; + + if(thisSliderVal >= scope.MAX_VALUE){ + scope.ngModel[i].value=scope.MAX_VALUE; + } + if(thisSliderVal <= prevSliderVal){ + scope.ngModel[i].value=prevSliderVal; + } + if(scope.gradient){ + colorString +=scope.ngModel[i].color+" "+scope.ngModel[i].value*100+"%,"; + } + else{ + colorString += scope.ngModel[i].color+" "+scope.ngModel[i-1].value*100+"%,"+scope.ngModel[i].color+" "+scope.ngModel[i].value*100+"%,"; + colorString += defaultColor+" "+scope.ngModel[i].value*100+"%,"+defaultColor; + } + } + } + // Update track bar color + colorString = colorString.substring(0,colorString.length-1); + var bc = "linear-gradient(left,"+colorString+")"; + //find track bar div + var track = angular.element(elem).find("div")[0].children[0]; + // multi-browser prefixes for linear-gradient (an empty element represents no prefix, i.e. 'linear-gradient') + ['-webkit-', '-moz-', '-o-', ''].forEach(function(prefix) { + angular.element(track).css('background', prefix + bc); + }); + },true); + } + }; + }) + .directive('vdsRange', function ($timeout) { + return { + template: '', + restrict: 'E', + replace: true, + scope: { + position: '=' + }, + link: function (scope, elem, attr) { + var RangeDataHelper = function(value, multiplier) { + this.value = isNaN(value)? 0 : value; + this.multiplier = multiplier; + Object.defineProperty(this, 'mulValue', { + get: function() { + return (parseFloat(this.value) * this.multiplier) +''; + }, + set: function(n) { + this.value = parseInt(n) / this.multiplier; + scope.position = this.value; + } + }); + }; + scope.$watch('position', function (n) { + if(typeof scope.rdh == 'undefined') { + scope.rdh = new RangeDataHelper(n, parseInt(attr.max) || 100); + } else { + // scope.rdh.multiplier = parseInt(attr.max) || 100; + scope.rdh.value = n; + } + }); + } + } + }); + +angular.module('vds.utils', ['angular.filter']) + .factory('vdsUtils', function($filter) { + var dayConst = 24*60*60*1000; + return { + time: { + fromTimeToValue: function (hours, minutes) { + var d = new Date(0); + d.setUTCHours(hours); + d.setUTCMinutes(minutes); + return d.getTime() / dayConst; + }, + fromTimeStringToValue: function(time){ + var d = new Date("1970-01-01 "+time.trim()+"+0000"); + return d.getTime() / dayConst; + }, + fromValueToTime: function (value) { + var d = new Date(Math.ceil(dayConst * value)); + if (d.getMilliseconds() >= 500){ + d.setMilliseconds(1000); + } + var h = d.getUTCHours() + ( (d.getUTCDate()-1) * 24 ); + var m = d.getUTCMinutes(); + return { + hours: h, + minutes: m, + label: d.getUTCDate() === 1 ? $filter('date')(d, "HH:mm", "+0000") : "24:00" + }; + }, + fromDateToTimeString: function(date){ + return $filter('date')(date, "HH:mm"); + }, + fromTimeSringToDate: function(time){ + return new Date("2016-06-01 "+time.trim()); + } + }, + format: { + padZeroes: function (num, size) { + var s = "000000000" + num; + return s.substr(s.length-size); + } + } + } + }); diff --git a/src/main/resources/static/module/angular-nouislider/nouislider.js b/src/main/resources/static/module/angular-nouislider/nouislider.js new file mode 100644 index 0000000..d9afa6c --- /dev/null +++ b/src/main/resources/static/module/angular-nouislider/nouislider.js @@ -0,0 +1,85 @@ +'use strict'; +angular.module('nouislider', []).directive('slider', function () { + return { + restrict: 'A', + scope: { + start: '@', + step: '@', + end: '@', + callback: '@', + margin: '@', + ngModel: '=', + ngFrom: '=', + ngTo: '=' + }, + link: function (scope, element, attrs) { + var callback, fromParsed, parsedValue, slider, toParsed; + slider = $(element); + callback = scope.callback ? scope.callback : 'slide'; + if (scope.ngFrom != null && scope.ngTo != null) { + fromParsed = null; + toParsed = null; + slider.noUiSlider({ + start: [ + scope.ngFrom || scope.start, + scope.ngTo || scope.end + ], + step: parseFloat(scope.step || 1), + connect: true, + margin: parseFloat(scope.margin || 0), + range: { + min: [parseFloat(scope.start)], + max: [parseFloat(scope.end)] + } + }); + slider.on(callback, function () { + var from, to, _ref; + _ref = slider.val(), from = _ref[0], to = _ref[1]; + fromParsed = parseFloat(from); + toParsed = parseFloat(to); + return scope.$apply(function () { + scope.ngFrom = fromParsed; + return scope.ngTo = toParsed; + }); + }); + scope.$watch('ngFrom', function (newVal, oldVal) { + if (newVal !== fromParsed) { + return slider.val([ + newVal, + null + ]); + } + }); + return scope.$watch('ngTo', function (newVal, oldVal) { + if (newVal !== toParsed) { + return slider.val([ + null, + newVal + ]); + } + }); + } else { + parsedValue = null; + slider.noUiSlider({ + start: [scope.ngModel || scope.start], + step: parseFloat(scope.step || 1), + range: { + min: [parseFloat(scope.start)], + max: [parseFloat(scope.end)] + } + }); + slider.on(callback, function () { + parsedValue = parseFloat(slider.val()); + return scope.$apply(function () { + return scope.ngModel = parsedValue; + }); + }); + return scope.$watch('ngModel', function (newVal, oldVal) { + if (newVal !== parsedValue) { + return slider.val(newVal); + } + }); + } + } + }; +}); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-nouislider/nouislider.min.js b/src/main/resources/static/module/angular-nouislider/nouislider.min.js new file mode 100644 index 0000000..19db5ca --- /dev/null +++ b/src/main/resources/static/module/angular-nouislider/nouislider.min.js @@ -0,0 +1 @@ +"use strict";angular.module("nouislider",[]).directive("slider",function(){return{restrict:"A",scope:{start:"@",step:"@",end:"@",callback:"@",margin:"@",ngModel:"=",ngFrom:"=",ngTo:"="},link:function(a,b){var c,d,e,f,g;return f=$(b),c=a.callback?a.callback:"slide",null!=a.ngFrom&&null!=a.ngTo?(d=null,g=null,f.noUiSlider({start:[a.ngFrom||a.start,a.ngTo||a.end],step:parseFloat(a.step||1),connect:!0,margin:parseFloat(a.margin||0),range:{min:[parseFloat(a.start)],max:[parseFloat(a.end)]}}),f.on(c,function(){var b,c,e;return e=f.val(),b=e[0],c=e[1],d=parseFloat(b),g=parseFloat(c),a.$apply(function(){return a.ngFrom=d,a.ngTo=g})}),a.$watch("ngFrom",function(a){return a!==d?f.val([a,null]):void 0}),a.$watch("ngTo",function(a){return a!==g?f.val([null,a]):void 0})):(e=null,f.noUiSlider({start:[a.ngModel||a.start],step:parseFloat(a.step||1),range:{min:[parseFloat(a.start)],max:[parseFloat(a.end)]}}),f.on(c,function(){return e=parseFloat(f.val()),a.$apply(function(){return a.ngModel=e})}),a.$watch("ngModel",function(a){return a!==e?f.val(a):void 0}))}}}); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-nvd3/angular-nvd3.js b/src/main/resources/static/module/angular-nvd3/angular-nvd3.js new file mode 100644 index 0000000..84e4059 --- /dev/null +++ b/src/main/resources/static/module/angular-nvd3/angular-nvd3.js @@ -0,0 +1,653 @@ +/************************************************************************** +* AngularJS-nvD3, v1.0.9; MIT +* http://krispo.github.io/angular-nvd3 +**************************************************************************/ +(function(window){ + + 'use strict'; + var nv = window.nv; + + // Node.js or CommonJS + if (typeof(exports) !== 'undefined') { + /* jshint -W020 */ + nv = require('nvd3'); + /* jshint +W020 */ + } + + angular.module('nvd3', []) + + .directive('nvd3', ['nvd3Utils', function(nvd3Utils){ + return { + restrict: 'AE', + scope: { + data: '=', //chart data, [required] + options: '=', //chart options, according to nvd3 core api, [required] + api: '=?', //directive global api, [optional] + events: '=?', //global events that directive would subscribe to, [optional] + config: '=?', //global directive configuration, [optional] + onReady: '&?' //callback function that is called with internal scope when directive is created [optional] + }, + link: function(scope, element, attrs){ + var defaultConfig = { + extended: false, + visible: true, + disabled: false, + refreshDataOnly: true, + deepWatchOptions: true, + deepWatchData: true, + deepWatchDataDepth: 2, // 0 - by reference (cheap), 1 - by collection item (the middle), 2 - by value (expensive) + debounce: 10, // default 10ms, time silence to prevent refresh while multiple options changes at a time + debounceImmediate: true // immediate flag for debounce function + }; + + //flag indicates if directive and chart is ready + scope.isReady = false; + + //basic directive configuration + scope._config = angular.extend(defaultConfig, scope.config); + + //directive global api + scope.api = { + // Fully refresh directive + refresh: function(){ + scope.api.updateWithOptions(); + scope.isReady = true; + }, + + // Fully refresh directive with specified timeout + refreshWithTimeout: function(t){ + setTimeout(function(){ + scope.api.refresh(); + }, t); + }, + + // Update chart layout (for example if container is resized) + update: function() { + if (scope.chart && scope.svg) { + if (scope.options.chart.type === 'sunburstChart') { + scope.svg.datum(angular.copy(scope.data)).call(scope.chart); + } else { + scope.svg.datum(scope.data).call(scope.chart); + } + } else { + scope.api.refresh(); + } + }, + + // Update chart layout with specified timeout + updateWithTimeout: function(t){ + setTimeout(function(){ + scope.api.update(); + }, t); + }, + + // Update chart with new options + updateWithOptions: function(options){ + // set options + if (!arguments.length) { + options = scope.options; + } else { + scope.options = options; + + // return if options $watch is enabled + if (scope._config.deepWatchOptions && !scope._config.disabled) return; + } + + // Clearing + scope.api.clearElement(); + + // Exit if options are not yet bound + if (angular.isDefined(options) === false) return; + + // Exit if chart is hidden + if (!scope._config.visible) return; + + // Initialize chart with specific type + scope.chart = nv.models[options.chart.type](); + + // Generate random chart ID + scope.chart.id = Math.random().toString(36).substr(2, 15); + + angular.forEach(scope.chart, function(value, key){ + if (key[0] === '_'); + else if ([ + 'clearHighlights', + 'highlightPoint', + 'id', + 'options', + 'resizeHandler', + 'state', + 'open', + 'close', + 'tooltipContent' + ].indexOf(key) >= 0); + + else if (key === 'dispatch') { + if (options.chart[key] === undefined || options.chart[key] === null) { + if (scope._config.extended) options.chart[key] = {}; + } + configureEvents(scope.chart[key], options.chart[key]); + } + + else if ([ + 'bars', + 'bars1', + 'bars2', + 'boxplot', + 'bullet', + 'controls', + 'discretebar', + 'distX', + 'distY', + 'focus', + 'interactiveLayer', + 'legend', + 'lines', + 'lines1', + 'lines2', + 'multibar', + 'pie', + 'scatter', + 'scatters1', + 'scatters2', + 'sparkline', + 'stack1', + 'stack2', + 'sunburst', + 'tooltip', + 'x2Axis', + 'xAxis', + 'y1Axis', + 'y2Axis', + 'y3Axis', + 'y4Axis', + 'yAxis', + 'yAxis1', + 'yAxis2' + ].indexOf(key) >= 0 || + // stacked is a component for stackedAreaChart, but a boolean for multiBarChart and multiBarHorizontalChart + (key === 'stacked' && options.chart.type === 'stackedAreaChart')) { + if (options.chart[key] === undefined || options.chart[key] === null) { + if (scope._config.extended) options.chart[key] = {}; + } + configure(scope.chart[key], options.chart[key], options.chart.type); + } + + //TODO: need to fix bug in nvd3 + else if ((key === 'focusHeight') && options.chart.type === 'lineChart'); + else if ((key === 'focusHeight') && options.chart.type === 'lineWithFocusChart'); + else if ((key === 'xTickFormat' || key === 'yTickFormat') && options.chart.type === 'lineWithFocusChart'); + else if ((key === 'tooltips') && options.chart.type === 'boxPlotChart'); + else if ((key === 'tooltipXContent' || key === 'tooltipYContent') && options.chart.type === 'scatterChart'); + else if ((key === 'x' || key === 'y') && options.chart.type === 'forceDirectedGraph'); + + else if (options.chart[key] === undefined || options.chart[key] === null){ + if (scope._config.extended) { + if (key==='barColor') + options.chart[key] = value()(); + else + options.chart[key] = value(); + } + } + + else scope.chart[key](options.chart[key]); + }); + + // Update with data + scope.api.updateWithData(); + + // Configure wrappers + if (options['title'] || scope._config.extended) configureWrapper('title'); + if (options['subtitle'] || scope._config.extended) configureWrapper('subtitle'); + if (options['caption'] || scope._config.extended) configureWrapper('caption'); + + + // Configure styles + if (options['styles'] || scope._config.extended) configureStyles(); + + nv.addGraph(function() { + if (!scope.chart) return; + + // Remove resize handler. Due to async execution should be placed here, not in the clearElement + if (scope.chart.resizeHandler) scope.chart.resizeHandler.clear(); + + // Update the chart when window resizes + scope.chart.resizeHandler = nv.utils.windowResize(function() { + scope.chart && scope.chart.update && scope.chart.update(); + }); + + /// Zoom feature + if (options.chart.zoom !== undefined && [ + 'scatterChart', + 'lineChart', + 'candlestickBarChart', + 'cumulativeLineChart', + 'historicalBarChart', + 'ohlcBarChart', + 'stackedAreaChart' + ].indexOf(options.chart.type) > -1) { + nvd3Utils.zoom(scope, options); + } + + return scope.chart; + }, options.chart['callback']); + }, + + // Update chart with new data + updateWithData: function (data){ + // set data + if (!arguments.length) { + if (scope.options.chart.type === 'sunburstChart') { + data = angular.copy(scope.data); + } else { + data = scope.data; + } + } else { + scope.data = data; + + // return if data $watch is enabled + if (scope._config.deepWatchData && !scope._config.disabled) return; + } + + if (data) { + // remove whole svg element with old data + d3.select(element[0]).select('svg').remove(); + + var h, w; + + // Select the current element to add element and to render the chart in + scope.svg = d3.select(element[0]).insert('svg', '.caption'); + if (h = scope.options.chart.height) { + if (!isNaN(+h)) h += 'px'; //check if height is number + scope.svg.attr('height', h).style({height: h}); + } + if (w = scope.options.chart.width) { + if (!isNaN(+w)) w += 'px'; //check if width is number + scope.svg.attr('width', w).style({width: w}); + } else { + scope.svg.attr('width', '100%').style({width: '100%'}); + } + + scope.svg.datum(data).call(scope.chart); + + // update zooming if exists + if (scope.chart && scope.chart.zoomRender) scope.chart.zoomRender(); + } + }, + + // Fully clear directive element + clearElement: function (){ + element.find('.title').remove(); + element.find('.subtitle').remove(); + element.find('.caption').remove(); + element.empty(); + + // remove tooltip if exists + if (scope.chart && scope.chart.tooltip && scope.chart.tooltip.id) { + d3.select('#' + scope.chart.tooltip.id()).remove(); + } + + // To be compatible with old nvd3 (v1.7.1) + if (nv.graphs && scope.chart) { + for (var i = nv.graphs.length - 1; i >= 0; i--) { + if (nv.graphs[i] && (nv.graphs[i].id === scope.chart.id)) { + nv.graphs.splice(i, 1); + } + } + } + if (nv.tooltip && nv.tooltip.cleanup) { + nv.tooltip.cleanup(); + } + if (scope.chart && scope.chart.resizeHandler) scope.chart.resizeHandler.clear(); + scope.chart = null; + }, + + // Get full directive scope + getScope: function(){ return scope; }, + + // Get directive element + getElement: function(){ return element; } + }; + + // Configure the chart model with the passed options + function configure(chart, options, chartType){ + if (chart && options){ + angular.forEach(chart, function(value, key){ + if (key[0] === '_'); + else if (key === 'dispatch') { + if (options[key] === undefined || options[key] === null) { + if (scope._config.extended) options[key] = {}; + } + configureEvents(value, options[key]); + } + else if (key === 'tooltip') { + if (options[key] === undefined || options[key] === null) { + if (scope._config.extended) options[key] = {}; + } + configure(chart[key], options[key], chartType); + } + else if (key === 'contentGenerator') { + if (options[key]) chart[key](options[key]); + } + else if ([ + 'axis', + 'clearHighlights', + 'defined', + 'highlightPoint', + 'nvPointerEventsClass', + 'options', + 'rangeBand', + 'rangeBands', + 'scatter', + 'open', + 'close', + 'node' + ].indexOf(key) === -1) { + if (options[key] === undefined || options[key] === null){ + if (scope._config.extended) options[key] = value(); + } + else chart[key](options[key]); + } + }); + } + } + + // Subscribe to the chart events (contained in 'dispatch') + // and pass eventHandler functions in the 'options' parameter + function configureEvents(dispatch, options){ + if (dispatch && options){ + angular.forEach(dispatch, function(value, key){ + if (options[key] === undefined || options[key] === null){ + if (scope._config.extended) options[key] = value.on; + } + else dispatch.on(key + '._', options[key]); + }); + } + } + + // Configure 'title', 'subtitle', 'caption'. + // nvd3 has no sufficient models for it yet. + function configureWrapper(name){ + var _ = nvd3Utils.deepExtend(defaultWrapper(name), scope.options[name] || {}); + + if (scope._config.extended) scope.options[name] = _; + + var wrapElement = angular.element('
').html(_['html'] || '') + .addClass(name).addClass(_.className) + .removeAttr('style') + .css(_.css); + + if (!_['html']) wrapElement.text(_.text); + + if (_.enable) { + if (name === 'title') element.prepend(wrapElement); + else if (name === 'subtitle') angular.element(element[0].querySelector('.title')).after(wrapElement); + else if (name === 'caption') element.append(wrapElement); + } + } + + // Add some styles to the whole directive element + function configureStyles(){ + var _ = nvd3Utils.deepExtend(defaultStyles(), scope.options['styles'] || {}); + + if (scope._config.extended) scope.options['styles'] = _; + + angular.forEach(_.classes, function(value, key){ + value ? element.addClass(key) : element.removeClass(key); + }); + + element.removeAttr('style').css(_.css); + } + + // Default values for 'title', 'subtitle', 'caption' + function defaultWrapper(_){ + switch (_){ + case 'title': return { + enable: false, + text: 'Write Your Title', + className: 'h4', + css: { + width: scope.options.chart.width + 'px', + textAlign: 'center' + } + }; + case 'subtitle': return { + enable: false, + text: 'Write Your Subtitle', + css: { + width: scope.options.chart.width + 'px', + textAlign: 'center' + } + }; + case 'caption': return { + enable: false, + text: 'Figure 1. Write Your Caption text.', + css: { + width: scope.options.chart.width + 'px', + textAlign: 'center' + } + }; + } + } + + // Default values for styles + function defaultStyles(){ + return { + classes: { + 'with-3d-shadow': true, + 'with-transitions': true, + 'gallery': false + }, + css: {} + }; + } + + /* Event Handling */ + // Watching on options changing + if (scope._config.deepWatchOptions) { + scope.$watch('options', nvd3Utils.debounce(function(newOptions){ + if (!scope._config.disabled) scope.api.refresh(); + }, scope._config.debounce, scope._config.debounceImmediate), true); + } + + // Watching on data changing + function dataWatchFn(newData, oldData) { + if (newData !== oldData){ + if (!scope._config.disabled) { + scope._config.refreshDataOnly ? scope.api.update() : scope.api.refresh(); // if wanted to refresh data only, use update method, otherwise use full refresh. + } + } + } + if (scope._config.deepWatchData) { + if (scope._config.deepWatchDataDepth === 1) { + scope.$watchCollection('data', dataWatchFn); + } else { + scope.$watch('data', dataWatchFn, scope._config.deepWatchDataDepth === 2); + } + } + + // Watching on config changing + scope.$watch('config', function(newConfig, oldConfig){ + if (newConfig !== oldConfig){ + scope._config = angular.extend(defaultConfig, newConfig); + scope.api.refresh(); + } + }, true); + + // Refresh chart first time if deepWatchOptions and deepWatchData are false + if (!scope._config.deepWatchOptions && !scope._config.deepWatchData) { + scope.api.refresh(); + } + + //subscribe on global events + angular.forEach(scope.events, function(eventHandler, event){ + scope.$on(event, function(e, args){ + return eventHandler(e, scope, args); + }); + }); + + // remove completely when directive is destroyed + element.on('$destroy', function () { + scope.api.clearElement(); + }); + + // trigger onReady callback if directive is ready + scope.$watch('isReady', function(isReady){ + if (isReady) { + if (scope.onReady && typeof scope.onReady() === 'function') scope.onReady()(scope, element); + } + }); + } + }; + }]) + + .factory('nvd3Utils', function(){ + return { + debounce: function(func, wait, immediate) { + var timeout; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; + }, + deepExtend: function(dst){ + var me = this; + angular.forEach(arguments, function(obj) { + if (obj !== dst) { + angular.forEach(obj, function(value, key) { + if (dst[key] && dst[key].constructor && dst[key].constructor === Object) { + me.deepExtend(dst[key], value); + } else { + dst[key] = value; + } + }); + } + }); + return dst; + }, + zoom: function(scope, options) { + var zoom = options.chart.zoom; + + // check if zoom enabled + var enabled = (typeof zoom.enabled === 'undefined' || zoom.enabled === null) ? true : zoom.enabled; + if (!enabled) return; + + var xScale = scope.chart.xAxis.scale() + , yScale = scope.chart.yAxis.scale() + , xDomain = scope.chart.xDomain || xScale.domain + , yDomain = scope.chart.yDomain || yScale.domain + , x_boundary = xScale.domain().slice() + , y_boundary = yScale.domain().slice() + + // initialize zoom options + , scale = zoom.scale || 1 + , translate = zoom.translate || [0, 0] + , scaleExtent = zoom.scaleExtent || [1, 10] + , useFixedDomain = zoom.useFixedDomain || false + , useNiceScale = zoom.useNiceScale || false + , horizontalOff = zoom.horizontalOff || false + , verticalOff = zoom.verticalOff || false + , unzoomEventType = zoom.unzoomEventType || 'dblclick.zoom' + + // auxiliary functions + , fixDomain + , d3zoom + , zoomed + , unzoomed + , zoomend + ; + + // ensure nice axis + if (useNiceScale) { + xScale.nice(); + yScale.nice(); + } + + // fix domain + fixDomain = function (domain, boundary) { + domain[0] = Math.min(Math.max(domain[0], boundary[0]), boundary[1] - boundary[1] / scaleExtent[1]); + domain[1] = Math.max(boundary[0] + boundary[1] / scaleExtent[1], Math.min(domain[1], boundary[1])); + return domain; + }; + + // zoom event handler + zoomed = function () { + if (zoom.zoomed !== undefined) { + var domains = zoom.zoomed(xScale.domain(), yScale.domain()); + if (!horizontalOff) xDomain([domains.x1, domains.x2]); + if (!verticalOff) yDomain([domains.y1, domains.y2]); + } else { + if (!horizontalOff) xDomain(useFixedDomain ? fixDomain(xScale.domain(), x_boundary) : xScale.domain()); + if (!verticalOff) yDomain(useFixedDomain ? fixDomain(yScale.domain(), y_boundary) : yScale.domain()); + } + if (scope.chart) scope.chart.update(); + }; + + // unzoomed event handler + unzoomed = function () { + if (zoom.unzoomed !== undefined) { + var domains = zoom.unzoomed(xScale.domain(), yScale.domain()); + if (!horizontalOff) xDomain([domains.x1, domains.x2]); + if (!verticalOff) yDomain([domains.y1, domains.y2]); + } else { + if (!horizontalOff) xDomain(x_boundary); + if (!verticalOff) yDomain(y_boundary); + } + d3zoom.scale(scale).translate(translate); + if (scope.chart) scope.chart.update(); + }; + + // zoomend event handler + zoomend = function () { + if (zoom.zoomend !== undefined) { + zoom.zoomend(); + } + }; + + // create d3 zoom handler + d3zoom = d3.behavior.zoom() + .x(xScale) + .y(yScale) + .scaleExtent(scaleExtent) + .on('zoom', zoomed) + .on('zoomend', zoomend); + + if (scope.svg) { + scope.svg.call(d3zoom); + + d3zoom.scale(scale).translate(translate).event(scope.svg); + + if (unzoomEventType !== 'none') scope.svg.on(unzoomEventType, unzoomed); + } + + if (scope.chart) + scope.chart.zoomRender = function(){ + // reset zoom scale and translate + d3zoom.scale(scale).translate(translate); + + // update scale + xScale = scope.chart.xAxis.scale(); + yScale = scope.chart.yAxis.scale(); + xDomain = scope.chart.xDomain || xScale.domain; + yDomain = scope.chart.yDomain || yScale.domain; + x_boundary = xScale.domain().slice(); + y_boundary = yScale.domain().slice(); + + // update zoom scale + d3zoom.x(xScale).y(yScale); + + scope.svg.call(d3zoom); + + if (unzoomEventType !== 'none') scope.svg.on(unzoomEventType, unzoomed); + }; + } + }; + }); +})(window); diff --git a/src/main/resources/static/module/angular-nvd3/angular-nvd3.min.js b/src/main/resources/static/module/angular-nvd3/angular-nvd3.min.js new file mode 100644 index 0000000..4aced57 --- /dev/null +++ b/src/main/resources/static/module/angular-nvd3/angular-nvd3.min.js @@ -0,0 +1 @@ +!function(window){"use strict";var nv=window.nv;"undefined"!=typeof exports&&(nv=require("nvd3")),angular.module("nvd3",[]).directive("nvd3",["nvd3Utils",function(nvd3Utils){return{restrict:"AE",scope:{data:"=",options:"=",api:"=?",events:"=?",config:"=?",onReady:"&?"},link:function(scope,element,attrs){function configure(chart,options,chartType){chart&&options&&angular.forEach(chart,function(value,key){"_"===key[0]||("dispatch"===key?(void 0!==options[key]&&null!==options[key]||scope._config.extended&&(options[key]={}),configureEvents(value,options[key])):"tooltip"===key?(void 0!==options[key]&&null!==options[key]||scope._config.extended&&(options[key]={}),configure(chart[key],options[key],chartType)):"contentGenerator"===key?options[key]&&chart[key](options[key]):-1===["axis","clearHighlights","defined","highlightPoint","nvPointerEventsClass","options","rangeBand","rangeBands","scatter","open","close","node"].indexOf(key)&&(void 0===options[key]||null===options[key]?scope._config.extended&&(options[key]=value()):chart[key](options[key])))})}function configureEvents(dispatch,options){dispatch&&options&&angular.forEach(dispatch,function(value,key){void 0===options[key]||null===options[key]?scope._config.extended&&(options[key]=value.on):dispatch.on(key+"._",options[key])})}function configureWrapper(name){var _=nvd3Utils.deepExtend(defaultWrapper(name),scope.options[name]||{});scope._config.extended&&(scope.options[name]=_);var wrapElement=angular.element("
").html(_.html||"").addClass(name).addClass(_.className).removeAttr("style").css(_.css);_.html||wrapElement.text(_.text),_.enable&&("title"===name?element.prepend(wrapElement):"subtitle"===name?angular.element(element[0].querySelector(".title")).after(wrapElement):"caption"===name&&element.append(wrapElement))}function configureStyles(){var _=nvd3Utils.deepExtend(defaultStyles(),scope.options.styles||{});scope._config.extended&&(scope.options.styles=_),angular.forEach(_.classes,function(value,key){value?element.addClass(key):element.removeClass(key)}),element.removeAttr("style").css(_.css)}function defaultWrapper(_){switch(_){case"title":return{enable:!1,text:"Write Your Title",className:"h4",css:{width:scope.options.chart.width+"px",textAlign:"center"}};case"subtitle":return{enable:!1,text:"Write Your Subtitle",css:{width:scope.options.chart.width+"px",textAlign:"center"}};case"caption":return{enable:!1,text:"Figure 1. Write Your Caption text.",css:{width:scope.options.chart.width+"px",textAlign:"center"}}}}function defaultStyles(){return{classes:{"with-3d-shadow":!0,"with-transitions":!0,gallery:!1},css:{}}}function dataWatchFn(newData,oldData){newData!==oldData&&(scope._config.disabled||(scope._config.refreshDataOnly?scope.api.update():scope.api.refresh()))}var defaultConfig={extended:!1,visible:!0,disabled:!1,refreshDataOnly:!0,deepWatchOptions:!0,deepWatchData:!0,deepWatchDataDepth:2,debounce:10,debounceImmediate:!0};scope.isReady=!1,scope._config=angular.extend(defaultConfig,scope.config),scope.api={refresh:function(){scope.api.updateWithOptions(),scope.isReady=!0},refreshWithTimeout:function(t){setTimeout(function(){scope.api.refresh()},t)},update:function(){scope.chart&&scope.svg?"sunburstChart"===scope.options.chart.type?scope.svg.datum(angular.copy(scope.data)).call(scope.chart):scope.svg.datum(scope.data).call(scope.chart):scope.api.refresh()},updateWithTimeout:function(t){setTimeout(function(){scope.api.update()},t)},updateWithOptions:function(options){if(arguments.length){if(scope.options=options,scope._config.deepWatchOptions&&!scope._config.disabled)return}else options=scope.options;scope.api.clearElement(),angular.isDefined(options)!==!1&&scope._config.visible&&(scope.chart=nv.models[options.chart.type](),scope.chart.id=Math.random().toString(36).substr(2,15),angular.forEach(scope.chart,function(value,key){"_"===key[0]||["clearHighlights","highlightPoint","id","options","resizeHandler","state","open","close","tooltipContent"].indexOf(key)>=0||("dispatch"===key?(void 0!==options.chart[key]&&null!==options.chart[key]||scope._config.extended&&(options.chart[key]={}),configureEvents(scope.chart[key],options.chart[key])):["bars","bars1","bars2","boxplot","bullet","controls","discretebar","distX","distY","focus","interactiveLayer","legend","lines","lines1","lines2","multibar","pie","scatter","scatters1","scatters2","sparkline","stack1","stack2","sunburst","tooltip","x2Axis","xAxis","y1Axis","y2Axis","y3Axis","y4Axis","yAxis","yAxis1","yAxis2"].indexOf(key)>=0||"stacked"===key&&"stackedAreaChart"===options.chart.type?(void 0!==options.chart[key]&&null!==options.chart[key]||scope._config.extended&&(options.chart[key]={}),configure(scope.chart[key],options.chart[key],options.chart.type)):"focusHeight"===key&&"lineChart"===options.chart.type||"focusHeight"===key&&"lineWithFocusChart"===options.chart.type||("xTickFormat"!==key&&"yTickFormat"!==key||"lineWithFocusChart"!==options.chart.type)&&("tooltips"===key&&"boxPlotChart"===options.chart.type||("tooltipXContent"!==key&&"tooltipYContent"!==key||"scatterChart"!==options.chart.type)&&("x"!==key&&"y"!==key||"forceDirectedGraph"!==options.chart.type)&&(void 0===options.chart[key]||null===options.chart[key]?scope._config.extended&&("barColor"===key?options.chart[key]=value()():options.chart[key]=value()):scope.chart[key](options.chart[key]))))}),scope.api.updateWithData(),(options.title||scope._config.extended)&&configureWrapper("title"),(options.subtitle||scope._config.extended)&&configureWrapper("subtitle"),(options.caption||scope._config.extended)&&configureWrapper("caption"),(options.styles||scope._config.extended)&&configureStyles(),nv.addGraph(function(){return scope.chart?(scope.chart.resizeHandler&&scope.chart.resizeHandler.clear(),scope.chart.resizeHandler=nv.utils.windowResize(function(){scope.chart&&scope.chart.update&&scope.chart.update()}),void 0!==options.chart.zoom&&["scatterChart","lineChart","candlestickBarChart","cumulativeLineChart","historicalBarChart","ohlcBarChart","stackedAreaChart"].indexOf(options.chart.type)>-1&&nvd3Utils.zoom(scope,options),scope.chart):void 0},options.chart.callback))},updateWithData:function(data){if(arguments.length){if(scope.data=data,scope._config.deepWatchData&&!scope._config.disabled)return}else data="sunburstChart"===scope.options.chart.type?angular.copy(scope.data):scope.data;if(data){d3.select(element[0]).select("svg").remove();var h,w;scope.svg=d3.select(element[0]).insert("svg",".caption"),(h=scope.options.chart.height)&&(isNaN(+h)||(h+="px"),scope.svg.attr("height",h).style({height:h})),(w=scope.options.chart.width)?(isNaN(+w)||(w+="px"),scope.svg.attr("width",w).style({width:w})):scope.svg.attr("width","100%").style({width:"100%"}),scope.svg.datum(data).call(scope.chart),scope.chart&&scope.chart.zoomRender&&scope.chart.zoomRender()}},clearElement:function(){if(element.find(".title").remove(),element.find(".subtitle").remove(),element.find(".caption").remove(),element.empty(),scope.chart&&scope.chart.tooltip&&scope.chart.tooltip.id&&d3.select("#"+scope.chart.tooltip.id()).remove(),nv.graphs&&scope.chart)for(var i=nv.graphs.length-1;i>=0;i--)nv.graphs[i]&&nv.graphs[i].id===scope.chart.id&&nv.graphs.splice(i,1);nv.tooltip&&nv.tooltip.cleanup&&nv.tooltip.cleanup(),scope.chart&&scope.chart.resizeHandler&&scope.chart.resizeHandler.clear(),scope.chart=null},getScope:function(){return scope},getElement:function(){return element}},scope._config.deepWatchOptions&&scope.$watch("options",nvd3Utils.debounce(function(newOptions){scope._config.disabled||scope.api.refresh()},scope._config.debounce,scope._config.debounceImmediate),!0),scope._config.deepWatchData&&(1===scope._config.deepWatchDataDepth?scope.$watchCollection("data",dataWatchFn):scope.$watch("data",dataWatchFn,2===scope._config.deepWatchDataDepth)),scope.$watch("config",function(newConfig,oldConfig){newConfig!==oldConfig&&(scope._config=angular.extend(defaultConfig,newConfig),scope.api.refresh())},!0),scope._config.deepWatchOptions||scope._config.deepWatchData||scope.api.refresh(),angular.forEach(scope.events,function(eventHandler,event){scope.$on(event,function(e,args){return eventHandler(e,scope,args)})}),element.on("$destroy",function(){scope.api.clearElement()}),scope.$watch("isReady",function(isReady){isReady&&scope.onReady&&"function"==typeof scope.onReady()&&scope.onReady()(scope,element)})}}}]).factory("nvd3Utils",function(){return{debounce:function(func,wait,immediate){var timeout;return function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)}},deepExtend:function(dst){var me=this;return angular.forEach(arguments,function(obj){obj!==dst&&angular.forEach(obj,function(value,key){dst[key]&&dst[key].constructor&&dst[key].constructor===Object?me.deepExtend(dst[key],value):dst[key]=value})}),dst},zoom:function(scope,options){var zoom=options.chart.zoom,enabled="undefined"==typeof zoom.enabled||null===zoom.enabled?!0:zoom.enabled;if(enabled){var fixDomain,d3zoom,zoomed,unzoomed,zoomend,xScale=scope.chart.xAxis.scale(),yScale=scope.chart.yAxis.scale(),xDomain=scope.chart.xDomain||xScale.domain,yDomain=scope.chart.yDomain||yScale.domain,x_boundary=xScale.domain().slice(),y_boundary=yScale.domain().slice(),scale=zoom.scale||1,translate=zoom.translate||[0,0],scaleExtent=zoom.scaleExtent||[1,10],useFixedDomain=zoom.useFixedDomain||!1,useNiceScale=zoom.useNiceScale||!1,horizontalOff=zoom.horizontalOff||!1,verticalOff=zoom.verticalOff||!1,unzoomEventType=zoom.unzoomEventType||"dblclick.zoom";useNiceScale&&(xScale.nice(),yScale.nice()),fixDomain=function(domain,boundary){return domain[0]=Math.min(Math.max(domain[0],boundary[0]),boundary[1]-boundary[1]/scaleExtent[1]),domain[1]=Math.max(boundary[0]+boundary[1]/scaleExtent[1],Math.min(domain[1],boundary[1])),domain},zoomed=function(){if(void 0!==zoom.zoomed){var domains=zoom.zoomed(xScale.domain(),yScale.domain());horizontalOff||xDomain([domains.x1,domains.x2]),verticalOff||yDomain([domains.y1,domains.y2])}else horizontalOff||xDomain(useFixedDomain?fixDomain(xScale.domain(),x_boundary):xScale.domain()),verticalOff||yDomain(useFixedDomain?fixDomain(yScale.domain(),y_boundary):yScale.domain());scope.chart&&scope.chart.update()},unzoomed=function(){if(void 0!==zoom.unzoomed){var domains=zoom.unzoomed(xScale.domain(),yScale.domain());horizontalOff||xDomain([domains.x1,domains.x2]),verticalOff||yDomain([domains.y1,domains.y2])}else horizontalOff||xDomain(x_boundary),verticalOff||yDomain(y_boundary);d3zoom.scale(scale).translate(translate),scope.chart&&scope.chart.update()},zoomend=function(){void 0!==zoom.zoomend&&zoom.zoomend()},d3zoom=d3.behavior.zoom().x(xScale).y(yScale).scaleExtent(scaleExtent).on("zoom",zoomed).on("zoomend",zoomend),scope.svg&&(scope.svg.call(d3zoom),d3zoom.scale(scale).translate(translate).event(scope.svg),"none"!==unzoomEventType&&scope.svg.on(unzoomEventType,unzoomed)),scope.chart&&(scope.chart.zoomRender=function(){d3zoom.scale(scale).translate(translate),xScale=scope.chart.xAxis.scale(),yScale=scope.chart.yAxis.scale(),xDomain=scope.chart.xDomain||xScale.domain,yDomain=scope.chart.yDomain||yScale.domain,x_boundary=xScale.domain().slice(),y_boundary=yScale.domain().slice(),d3zoom.x(xScale).y(yScale),scope.svg.call(d3zoom),"none"!==unzoomEventType&&scope.svg.on(unzoomEventType,unzoomed)})}}}})}(window); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.js b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.js new file mode 100644 index 0000000..7d35de4 --- /dev/null +++ b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.js @@ -0,0 +1,635 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= current) { + return fn(); + } + }; + _isValidLogObject = function(logObject) { + var isValid, j, len1; + isValid = false; + if (!logObject) { + return isValid; + } + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + isValid = (logObject[val] != null) && typeof logObject[val] === 'function'; + if (!isValid) { + break; + } + } + return isValid; + }; + + /* + Overide logeObject.debug with a nemDebug instance + see: https://github.com/visionmedia/debug/blob/master/Readme.md + */ + _wrapDebug = function(namespace, logObject) { + var debugInstance, j, len1, newLogger; + if (_debugCache[namespace] == null) { + _debugCache[namespace] = nemDebug(namespace); + } + debugInstance = _debugCache[namespace]; + newLogger = {}; + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + newLogger[val] = val === 'debug' ? debugInstance : logObject[val]; + } + return newLogger; + }; + Logger = (function() { + function Logger($log1) { + var fn1, j, len1, level, logFns; + this.$log = $log1; + this.spawn = bind(this.spawn, this); + if (!this.$log) { + throw 'internalLogger undefined'; + } + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + this.doLog = true; + logFns = {}; + fn1 = (function(_this) { + return function(level) { + logFns[level] = function() { + var args; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + if (_this.doLog) { + return _maybeExecLevel(LEVELS[level], _this.currentLevel, function() { + var ref; + return (ref = _this.$log)[level].apply(ref, args); + }); + } + }; + return _this[level] = logFns[level]; + }; + })(this); + for (j = 0, len1 = _fns.length; j < len1; j++) { + level = _fns[j]; + fn1(level); + } + this.LEVELS = LEVELS; + this.currentLevel = LEVELS.error; + } + + Logger.prototype.spawn = function(newInternalLogger) { + if (typeof newInternalLogger === 'string') { + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + if (!nemDebug) { + throw 'nemDebug is undefined this is probably the light version of this library sep debug logggers is not supported!'; + } + return _wrapDebug(newInternalLogger, this.$log); + } + return new Logger(newInternalLogger || this.$log); + }; + + return Logger; + + })(); + this.decorator = [ + '$log', function($delegate) { + var log; + log = new Logger($delegate); + log.currentLevel = LEVELS.debug; + return log; + } + ]; + this.$get = [ + '$log', function($log) { + return new Logger($log); + } + ]; + return this; + } +]); + +},{"debug":2}],2:[function(require,module,exports){ + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // is webkit? http://stackoverflow.com/a/16459606/376773 + return ('WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (window.console && (console.firebug || (console.exception && console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + return JSON.stringify(v); +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return args; + + var c = 'color: ' + this.color; + args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + return args; +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage(){ + try { + return window.localStorage; + } catch (e) {} +} + +},{"./debug":3}],3:[function(require,module,exports){ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = debug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lowercased letter, i.e. "n". + */ + +exports.formatters = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function selectColor() { + return exports.colors[prevColor++ % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function debug(namespace) { + + // define the `disabled` version + function disabled() { + } + disabled.enabled = false; + + // define the `enabled` version + function enabled() { + + var self = enabled; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // add the `color` if not set + if (null == self.useColors) self.useColors = exports.useColors(); + if (null == self.color && self.useColors) self.color = selectColor(); + + var args = Array.prototype.slice.call(arguments); + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %o + args = ['%o'].concat(args); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + if ('function' === typeof exports.formatArgs) { + args = exports.formatArgs.apply(self, args); + } + var logFn = enabled.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + enabled.enabled = true; + + var fn = exports.enabled(namespace) ? enabled : disabled; + + fn.namespace = namespace; + + return fn; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +},{"ms":4}],4:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options.long + ? long(val) + : short(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = '' + str; + if (str.length > 10000) return; + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function short(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function long(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +},{}]},{},[1]); diff --git a/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.light.js b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.light.js new file mode 100644 index 0000000..c1b165c --- /dev/null +++ b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.light.js @@ -0,0 +1,147 @@ +/** + * angular-simple-logger + * + * @version: 0.1.7 + * @author: Nicholas McCready + * @date: Tue Jan 26 2016 10:15:01 GMT-0500 (EST) + * @license: MIT + */ + +(function (window, angular){ + angular.module('nemLogging', []); + +angular.module('nemLogging').provider('nemDebug', function (){ + var ourDebug = null; + + this.$get = function(){ + //avail as service + return ourDebug; + }; + + //avail at provider, config time + this.debug = ourDebug; + + return this; +}); +var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + slice = [].slice; + +angular.module('nemLogging').provider('nemSimpleLogger', [ + 'nemDebugProvider', function(nemDebugProvider) { + var LEVELS, Logger, _debugCache, _fns, _isValidLogObject, _maybeExecLevel, _wrapDebug, i, key, len, nemDebug, val; + nemDebug = nemDebugProvider.debug; + _debugCache = {}; + _fns = ['debug', 'info', 'warn', 'error', 'log']; + LEVELS = {}; + for (key = i = 0, len = _fns.length; i < len; key = ++i) { + val = _fns[key]; + LEVELS[val] = key; + } + _maybeExecLevel = function(level, current, fn) { + if (level >= current) { + return fn(); + } + }; + _isValidLogObject = function(logObject) { + var isValid, j, len1; + isValid = false; + if (!logObject) { + return isValid; + } + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + isValid = (logObject[val] != null) && typeof logObject[val] === 'function'; + if (!isValid) { + break; + } + } + return isValid; + }; + + /* + Overide logeObject.debug with a nemDebug instance + see: https://github.com/visionmedia/debug/blob/master/Readme.md + */ + _wrapDebug = function(namespace, logObject) { + var debugInstance, j, len1, newLogger; + if (_debugCache[namespace] == null) { + _debugCache[namespace] = nemDebug(namespace); + } + debugInstance = _debugCache[namespace]; + newLogger = {}; + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + newLogger[val] = val === 'debug' ? debugInstance : logObject[val]; + } + return newLogger; + }; + Logger = (function() { + function Logger($log1) { + var fn1, j, len1, level, logFns; + this.$log = $log1; + this.spawn = bind(this.spawn, this); + if (!this.$log) { + throw 'internalLogger undefined'; + } + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + this.doLog = true; + logFns = {}; + fn1 = (function(_this) { + return function(level) { + logFns[level] = function() { + var args; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + if (_this.doLog) { + return _maybeExecLevel(LEVELS[level], _this.currentLevel, function() { + var ref; + return (ref = _this.$log)[level].apply(ref, args); + }); + } + }; + return _this[level] = logFns[level]; + }; + })(this); + for (j = 0, len1 = _fns.length; j < len1; j++) { + level = _fns[j]; + fn1(level); + } + this.LEVELS = LEVELS; + this.currentLevel = LEVELS.error; + } + + Logger.prototype.spawn = function(newInternalLogger) { + if (typeof newInternalLogger === 'string') { + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + if (!nemDebug) { + throw 'nemDebug is undefined this is probably the light version of this library sep debug logggers is not supported!'; + } + return _wrapDebug(newInternalLogger, this.$log); + } + return new Logger(newInternalLogger || this.$log); + }; + + return Logger; + + })(); + this.decorator = [ + '$log', function($delegate) { + var log; + log = new Logger($delegate); + log.currentLevel = LEVELS.debug; + return log; + } + ]; + this.$get = [ + '$log', function($log) { + return new Logger($log); + } + ]; + return this; + } +]); + +})(window, angular); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.light.min.js b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.light.min.js new file mode 100644 index 0000000..9c00654 --- /dev/null +++ b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.light.min.js @@ -0,0 +1 @@ +!function(n,r){r.module("nemLogging",[]),r.module("nemLogging").provider("nemDebug",function(){var n=null;return this.$get=function(){return n},this.debug=n,this});var t=function(n,r){return function(){return n.apply(r,arguments)}},e=[].slice;r.module("nemLogging").provider("nemSimpleLogger",["nemDebugProvider",function(n){var r,i,o,u,g,l,s,f,h,a,c,d;for(c=n.debug,o={},u=["debug","info","warn","error","log"],r={},h=f=0,a=u.length;a>f;h=++f)d=u[h],r[d]=h;return l=function(n,r,t){return n>=r?t():void 0},g=function(n){var r,t,e;if(r=!1,!n)return r;for(t=0,e=u.length;e>t&&(d=u[t],r=null!=n[d]&&"function"==typeof n[d],r);t++);return r},s=function(n,r){var t,e,i,g;for(null==o[n]&&(o[n]=c(n)),t=o[n],g={},e=0,i=u.length;i>e;e++)d=u[e],g[d]="debug"===d?t:r[d];return g},i=function(){function n(n){var i,o,s,f,h;if(this.$log=n,this.spawn=t(this.spawn,this),!this.$log)throw"internalLogger undefined";if(!g(this.$log))throw"@$log is invalid";for(this.doLog=!0,h={},i=function(n){return function(t){return h[t]=function(){var i;return i=1<=arguments.length?e.call(arguments,0):[],n.doLog?l(r[t],n.currentLevel,function(){var r;return(r=n.$log)[t].apply(r,i)}):void 0},n[t]=h[t]}}(this),o=0,s=u.length;s>o;o++)f=u[o],i(f);this.LEVELS=r,this.currentLevel=r.error}return n.prototype.spawn=function(r){if("string"==typeof r){if(!g(this.$log))throw"@$log is invalid";if(!c)throw"nemDebug is undefined this is probably the light version of this library sep debug logggers is not supported!";return s(r,this.$log)}return new n(r||this.$log)},n}(),this.decorator=["$log",function(n){var t;return t=new i(n),t.currentLevel=r.debug,t}],this.$get=["$log",function(n){return new i(n)}],this}])}(window,angular); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.min.js b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.min.js new file mode 100644 index 0000000..9f2ade9 --- /dev/null +++ b/src/main/resources/static/module/angular-simple-logger/angular-simple-logger.min.js @@ -0,0 +1 @@ +!function e(r,n,o){function t(i,u){if(!n[i]){if(!r[i]){var a="function"==typeof require&&require;if(!u&&a)return a(i,!0);if(s)return s(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[i]={exports:{}};r[i][0].call(l.exports,function(e){var n=r[i][1][e];return t(n?n:e)},l,l.exports,e,r,n,o)}return n[i].exports}for(var s="function"==typeof require&&require,i=0;il;f=++l)h=i[f],r[h]=f;return a=function(e,r,n){return e>=r?n():void 0},u=function(e){var r,n,o;if(r=!1,!e)return r;for(n=0,o=i.length;o>n&&(h=i[n],r=null!=e[h]&&"function"==typeof e[h],r);n++);return r},c=function(e,r){var n,o,t,u;for(null==s[e]&&(s[e]=d(e)),n=s[e],u={},o=0,t=i.length;t>o;o++)h=i[o],u[h]="debug"===h?n:r[h];return u},n=function(){function e(e){var n,s,c,l,f;if(this.$log=e,this.spawn=o(this.spawn,this),!this.$log)throw"internalLogger undefined";if(!u(this.$log))throw"@$log is invalid";for(this.doLog=!0,f={},n=function(e){return function(n){return f[n]=function(){var o;return o=1<=arguments.length?t.call(arguments,0):[],e.doLog?a(r[n],e.currentLevel,function(){var r;return(r=e.$log)[n].apply(r,o)}):void 0},e[n]=f[n]}}(this),s=0,c=i.length;c>s;s++)l=i[s],n(l);this.LEVELS=r,this.currentLevel=r.error}return e.prototype.spawn=function(r){if("string"==typeof r){if(!u(this.$log))throw"@$log is invalid";if(!d)throw"nemDebug is undefined this is probably the light version of this library sep debug logggers is not supported!";return c(r,this.$log)}return new e(r||this.$log)},e}(),this.decorator=["$log",function(e){var o;return o=new n(e),o.currentLevel=r.debug,o}],this.$get=["$log",function(e){return new n(e)}],this}])},{debug:2}],2:[function(e,r,n){function o(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function t(){var e=arguments,r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+n.humanize(this.diff),!r)return e;var o="color: "+this.color;e=[e[0],o,"color: inherit"].concat(Array.prototype.slice.call(e,1));var t=0,s=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(t++,"%c"===e&&(s=t))}),e.splice(s,0,o),e}function s(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function i(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(r){}}function u(){var e;try{e=n.storage.debug}catch(r){}return e}function a(){try{return window.localStorage}catch(e){}}n=r.exports=e("./debug"),n.log=s,n.formatArgs=t,n.save=i,n.load=u,n.useColors=o,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:a(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(u())},{"./debug":3}],3:[function(e,r,n){function o(){return n.colors[l++%n.colors.length]}function t(e){function r(){}function t(){var e=t,r=+new Date,s=r-(c||r);e.diff=s,e.prev=c,e.curr=r,c=r,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=o());var i=Array.prototype.slice.call(arguments);i[0]=n.coerce(i[0]),"string"!=typeof i[0]&&(i=["%o"].concat(i));var u=0;i[0]=i[0].replace(/%([a-z%])/g,function(r,o){if("%%"===r)return r;u++;var t=n.formatters[o];if("function"==typeof t){var s=i[u];r=t.call(e,s),i.splice(u,1),u--}return r}),"function"==typeof n.formatArgs&&(i=n.formatArgs.apply(e,i));var a=t.log||n.log||console.log.bind(console);a.apply(e,i)}r.enabled=!1,t.enabled=!0;var s=n.enabled(e)?t:r;return s.namespace=e,s}function s(e){n.save(e);for(var r=(e||"").split(/[\s,]+/),o=r.length,t=0;o>t;t++)r[t]&&(e=r[t].replace(/\*/g,".*?"),"-"===e[0]?n.skips.push(new RegExp("^"+e.substr(1)+"$")):n.names.push(new RegExp("^"+e+"$")))}function i(){n.enable("")}function u(e){var r,o;for(r=0,o=n.skips.length;o>r;r++)if(n.skips[r].test(e))return!1;for(r=0,o=n.names.length;o>r;r++)if(n.names[r].test(e))return!0;return!1}function a(e){return e instanceof Error?e.stack||e.message:e}n=r.exports=t,n.coerce=a,n.disable=i,n.enable=s,n.enabled=u,n.humanize=e("ms"),n.names=[],n.skips=[],n.formatters={};var c,l=0},{ms:4}],4:[function(e,r,n){function o(e){if(e=""+e,!(e.length>1e4)){var r=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(r){var n=parseFloat(r[1]),o=(r[2]||"ms").toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return n*f;case"days":case"day":case"d":return n*l;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*u;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function t(e){return e>=l?Math.round(e/l)+"d":e>=c?Math.round(e/c)+"h":e>=a?Math.round(e/a)+"m":e>=u?Math.round(e/u)+"s":e+"ms"}function s(e){return i(e,l,"day")||i(e,c,"hour")||i(e,a,"minute")||i(e,u,"second")||e+" ms"}function i(e,r,n){return r>e?void 0:1.5*r>e?Math.floor(e/r)+" "+n:Math.ceil(e/r)+" "+n+"s"}var u=1e3,a=60*u,c=60*a,l=24*c,f=365.25*l;r.exports=function(e,r){return r=r||{},"string"==typeof e?o(e):r["long"]?s(e):t(e)}},{}]},{},[1]); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-simple-logger/browser.js b/src/main/resources/static/module/angular-simple-logger/browser.js new file mode 100644 index 0000000..7d35de4 --- /dev/null +++ b/src/main/resources/static/module/angular-simple-logger/browser.js @@ -0,0 +1,635 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= current) { + return fn(); + } + }; + _isValidLogObject = function(logObject) { + var isValid, j, len1; + isValid = false; + if (!logObject) { + return isValid; + } + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + isValid = (logObject[val] != null) && typeof logObject[val] === 'function'; + if (!isValid) { + break; + } + } + return isValid; + }; + + /* + Overide logeObject.debug with a nemDebug instance + see: https://github.com/visionmedia/debug/blob/master/Readme.md + */ + _wrapDebug = function(namespace, logObject) { + var debugInstance, j, len1, newLogger; + if (_debugCache[namespace] == null) { + _debugCache[namespace] = nemDebug(namespace); + } + debugInstance = _debugCache[namespace]; + newLogger = {}; + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + newLogger[val] = val === 'debug' ? debugInstance : logObject[val]; + } + return newLogger; + }; + Logger = (function() { + function Logger($log1) { + var fn1, j, len1, level, logFns; + this.$log = $log1; + this.spawn = bind(this.spawn, this); + if (!this.$log) { + throw 'internalLogger undefined'; + } + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + this.doLog = true; + logFns = {}; + fn1 = (function(_this) { + return function(level) { + logFns[level] = function() { + var args; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + if (_this.doLog) { + return _maybeExecLevel(LEVELS[level], _this.currentLevel, function() { + var ref; + return (ref = _this.$log)[level].apply(ref, args); + }); + } + }; + return _this[level] = logFns[level]; + }; + })(this); + for (j = 0, len1 = _fns.length; j < len1; j++) { + level = _fns[j]; + fn1(level); + } + this.LEVELS = LEVELS; + this.currentLevel = LEVELS.error; + } + + Logger.prototype.spawn = function(newInternalLogger) { + if (typeof newInternalLogger === 'string') { + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + if (!nemDebug) { + throw 'nemDebug is undefined this is probably the light version of this library sep debug logggers is not supported!'; + } + return _wrapDebug(newInternalLogger, this.$log); + } + return new Logger(newInternalLogger || this.$log); + }; + + return Logger; + + })(); + this.decorator = [ + '$log', function($delegate) { + var log; + log = new Logger($delegate); + log.currentLevel = LEVELS.debug; + return log; + } + ]; + this.$get = [ + '$log', function($log) { + return new Logger($log); + } + ]; + return this; + } +]); + +},{"debug":2}],2:[function(require,module,exports){ + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // is webkit? http://stackoverflow.com/a/16459606/376773 + return ('WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (window.console && (console.firebug || (console.exception && console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + return JSON.stringify(v); +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return args; + + var c = 'color: ' + this.color; + args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + return args; +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage(){ + try { + return window.localStorage; + } catch (e) {} +} + +},{"./debug":3}],3:[function(require,module,exports){ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = debug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lowercased letter, i.e. "n". + */ + +exports.formatters = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function selectColor() { + return exports.colors[prevColor++ % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function debug(namespace) { + + // define the `disabled` version + function disabled() { + } + disabled.enabled = false; + + // define the `enabled` version + function enabled() { + + var self = enabled; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // add the `color` if not set + if (null == self.useColors) self.useColors = exports.useColors(); + if (null == self.color && self.useColors) self.color = selectColor(); + + var args = Array.prototype.slice.call(arguments); + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %o + args = ['%o'].concat(args); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + if ('function' === typeof exports.formatArgs) { + args = exports.formatArgs.apply(self, args); + } + var logFn = enabled.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + enabled.enabled = true; + + var fn = exports.enabled(namespace) ? enabled : disabled; + + fn.namespace = namespace; + + return fn; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +},{"ms":4}],4:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options.long + ? long(val) + : short(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = '' + str; + if (str.length > 10000) return; + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function short(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function long(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +},{}]},{},[1]); diff --git a/src/main/resources/static/module/angular-simple-logger/index.js b/src/main/resources/static/module/angular-simple-logger/index.js new file mode 100644 index 0000000..78eb9b8 --- /dev/null +++ b/src/main/resources/static/module/angular-simple-logger/index.js @@ -0,0 +1,146 @@ +/** + * angular-simple-logger + * + * @version: 0.1.7 + * @author: Nicholas McCready + * @date: Tue Jan 26 2016 10:15:01 GMT-0500 (EST) + * @license: MIT + */ +var angular = require('angular'); + +angular.module('nemLogging', []); + +angular.module('nemLogging').provider('nemDebug', function (){ + var ourDebug = null; + ourDebug = require('debug'); + + this.$get = function(){ + //avail as service + return ourDebug; + }; + + //avail at provider, config time + this.debug = ourDebug; + + return this; +}); +var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + slice = [].slice; + +angular.module('nemLogging').provider('nemSimpleLogger', [ + 'nemDebugProvider', function(nemDebugProvider) { + var LEVELS, Logger, _debugCache, _fns, _isValidLogObject, _maybeExecLevel, _wrapDebug, i, key, len, nemDebug, val; + nemDebug = nemDebugProvider.debug; + _debugCache = {}; + _fns = ['debug', 'info', 'warn', 'error', 'log']; + LEVELS = {}; + for (key = i = 0, len = _fns.length; i < len; key = ++i) { + val = _fns[key]; + LEVELS[val] = key; + } + _maybeExecLevel = function(level, current, fn) { + if (level >= current) { + return fn(); + } + }; + _isValidLogObject = function(logObject) { + var isValid, j, len1; + isValid = false; + if (!logObject) { + return isValid; + } + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + isValid = (logObject[val] != null) && typeof logObject[val] === 'function'; + if (!isValid) { + break; + } + } + return isValid; + }; + + /* + Overide logeObject.debug with a nemDebug instance + see: https://github.com/visionmedia/debug/blob/master/Readme.md + */ + _wrapDebug = function(namespace, logObject) { + var debugInstance, j, len1, newLogger; + if (_debugCache[namespace] == null) { + _debugCache[namespace] = nemDebug(namespace); + } + debugInstance = _debugCache[namespace]; + newLogger = {}; + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + newLogger[val] = val === 'debug' ? debugInstance : logObject[val]; + } + return newLogger; + }; + Logger = (function() { + function Logger($log1) { + var fn1, j, len1, level, logFns; + this.$log = $log1; + this.spawn = bind(this.spawn, this); + if (!this.$log) { + throw 'internalLogger undefined'; + } + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + this.doLog = true; + logFns = {}; + fn1 = (function(_this) { + return function(level) { + logFns[level] = function() { + var args; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + if (_this.doLog) { + return _maybeExecLevel(LEVELS[level], _this.currentLevel, function() { + var ref; + return (ref = _this.$log)[level].apply(ref, args); + }); + } + }; + return _this[level] = logFns[level]; + }; + })(this); + for (j = 0, len1 = _fns.length; j < len1; j++) { + level = _fns[j]; + fn1(level); + } + this.LEVELS = LEVELS; + this.currentLevel = LEVELS.error; + } + + Logger.prototype.spawn = function(newInternalLogger) { + if (typeof newInternalLogger === 'string') { + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + if (!nemDebug) { + throw 'nemDebug is undefined this is probably the light version of this library sep debug logggers is not supported!'; + } + return _wrapDebug(newInternalLogger, this.$log); + } + return new Logger(newInternalLogger || this.$log); + }; + + return Logger; + + })(); + this.decorator = [ + '$log', function($delegate) { + var log; + log = new Logger($delegate); + log.currentLevel = LEVELS.debug; + return log; + } + ]; + this.$get = [ + '$log', function($log) { + return new Logger($log); + } + ]; + return this; + } +]); diff --git a/src/main/resources/static/module/angular-simple-logger/index.light.js b/src/main/resources/static/module/angular-simple-logger/index.light.js new file mode 100644 index 0000000..c1b165c --- /dev/null +++ b/src/main/resources/static/module/angular-simple-logger/index.light.js @@ -0,0 +1,147 @@ +/** + * angular-simple-logger + * + * @version: 0.1.7 + * @author: Nicholas McCready + * @date: Tue Jan 26 2016 10:15:01 GMT-0500 (EST) + * @license: MIT + */ + +(function (window, angular){ + angular.module('nemLogging', []); + +angular.module('nemLogging').provider('nemDebug', function (){ + var ourDebug = null; + + this.$get = function(){ + //avail as service + return ourDebug; + }; + + //avail at provider, config time + this.debug = ourDebug; + + return this; +}); +var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + slice = [].slice; + +angular.module('nemLogging').provider('nemSimpleLogger', [ + 'nemDebugProvider', function(nemDebugProvider) { + var LEVELS, Logger, _debugCache, _fns, _isValidLogObject, _maybeExecLevel, _wrapDebug, i, key, len, nemDebug, val; + nemDebug = nemDebugProvider.debug; + _debugCache = {}; + _fns = ['debug', 'info', 'warn', 'error', 'log']; + LEVELS = {}; + for (key = i = 0, len = _fns.length; i < len; key = ++i) { + val = _fns[key]; + LEVELS[val] = key; + } + _maybeExecLevel = function(level, current, fn) { + if (level >= current) { + return fn(); + } + }; + _isValidLogObject = function(logObject) { + var isValid, j, len1; + isValid = false; + if (!logObject) { + return isValid; + } + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + isValid = (logObject[val] != null) && typeof logObject[val] === 'function'; + if (!isValid) { + break; + } + } + return isValid; + }; + + /* + Overide logeObject.debug with a nemDebug instance + see: https://github.com/visionmedia/debug/blob/master/Readme.md + */ + _wrapDebug = function(namespace, logObject) { + var debugInstance, j, len1, newLogger; + if (_debugCache[namespace] == null) { + _debugCache[namespace] = nemDebug(namespace); + } + debugInstance = _debugCache[namespace]; + newLogger = {}; + for (j = 0, len1 = _fns.length; j < len1; j++) { + val = _fns[j]; + newLogger[val] = val === 'debug' ? debugInstance : logObject[val]; + } + return newLogger; + }; + Logger = (function() { + function Logger($log1) { + var fn1, j, len1, level, logFns; + this.$log = $log1; + this.spawn = bind(this.spawn, this); + if (!this.$log) { + throw 'internalLogger undefined'; + } + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + this.doLog = true; + logFns = {}; + fn1 = (function(_this) { + return function(level) { + logFns[level] = function() { + var args; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + if (_this.doLog) { + return _maybeExecLevel(LEVELS[level], _this.currentLevel, function() { + var ref; + return (ref = _this.$log)[level].apply(ref, args); + }); + } + }; + return _this[level] = logFns[level]; + }; + })(this); + for (j = 0, len1 = _fns.length; j < len1; j++) { + level = _fns[j]; + fn1(level); + } + this.LEVELS = LEVELS; + this.currentLevel = LEVELS.error; + } + + Logger.prototype.spawn = function(newInternalLogger) { + if (typeof newInternalLogger === 'string') { + if (!_isValidLogObject(this.$log)) { + throw '@$log is invalid'; + } + if (!nemDebug) { + throw 'nemDebug is undefined this is probably the light version of this library sep debug logggers is not supported!'; + } + return _wrapDebug(newInternalLogger, this.$log); + } + return new Logger(newInternalLogger || this.$log); + }; + + return Logger; + + })(); + this.decorator = [ + '$log', function($delegate) { + var log; + log = new Logger($delegate); + log.currentLevel = LEVELS.debug; + return log; + } + ]; + this.$get = [ + '$log', function($log) { + return new Logger($log); + } + ]; + return this; + } +]); + +})(window, angular); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.css b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.css new file mode 100644 index 0000000..a59d710 --- /dev/null +++ b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.css @@ -0,0 +1,131 @@ + +.tree-dnd-animate-enter, +.tree-dnd-node.ng-enter { + -webkit-transition: 0 linear all; + -moz-transition: 0 linear all; + -ms-transition: 0 linear all; + -o-transition: 0 linear all; + transition: 0 linear all; + position: relative; + display: block; + opacity: 0; + max-height: 0; +} + +.tree-dnd-animate-enter.tree-dnd-animate-enter-active, +.tree-dnd-node.ng-enter-active { + opacity: 1; + max-height: 30px; +} + +.tree-dnd-animate-leave, +.tree-dnd-node.ng-leave { + -webkit-transition: 0 linear all; + -moz-transition: 0 linear all; + -ms-transition: 0 linear all; + -o-transition: 0 linear all; + transition: 0 linear all; + position: relative; + display: block; + height: 30px; + max-height: 30px; + opacity: 1; +} + +.tree-dnd-animate-leave.tree-dnd-animate-leave-active, +.tree-dnd-node.ng-leave-active { + height: 0; + max-height: 0; + opacity: 0; +} + +.tree-dnd-node > td { + position: relative; +} + +.tree-dnd-animate.ng-enter { +} + +.tree-dnd .tree-icon, +.tree-label { + cursor: pointer; +} + +.tree-dnd > thead > tr > td, .tree-dnd > tbody > tr > td, .tree-dnd > tfoot > tr > td { + vertical-align: middle !important; +} + +.tree-dnd-empty { + border: 2px dashed #72da67 !important; + min-height: 100px; + background-color: #e5e5e5; +} + +.indented { + position: relative; +} + +.tree-dnd-hidden { + -webkit-animation: fadeOut 0s; + -moz-animation: fadeOut 0s; + -o-animation: fadeOut 0s; + animation: fadeOut 0s; + display: none !important; +} + +.tree-dnd-placeholder { + position: relative; + margin: 0px; + padding: 0px; + min-height: 20px; + line-height: 20px; +} + +.tree-dnd-handle { + cursor: pointer; + text-decoration: none; + font-weight: bold; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + min-height: 20px; + line-height: 20px; +} + +.tree-dnd-drag { + position: absolute; + pointer-events: none; + z-index: 999; + opacity: .7; + background-color: #cdffdc; + border: 2px dashed #385736; +} + +.tree-dnd-status { + position: absolute; + background-color: #ffffff; + border: 1px solid #92e5d3; + padding: 1px 4px; + opacity: .85; +} + +.tree-dnd-nodes { + margin: 0px; + padding: 0px; + list-style: none; +} + +.tree-dnd-nodes .tree-dnd-node { + border-radius: 0px !important; +} + +.tree-dnd-nodes .tree-dnd-nodes { + padding-left: 20px; +} + +.tree-dnd-node, .tree-dnd-placeholder { + /*margin: 0px;*/ + /*padding: 0px;*/ + min-height: 20px; + line-height: 20px; +} diff --git a/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.debug.js b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.debug.js new file mode 100644 index 0000000..cdac8f4 --- /dev/null +++ b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.debug.js @@ -0,0 +1,3397 @@ +/** + * The MIT License (MIT) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * @preserve + */ + +/** + * Implementing TreeDnD & Event DrapnDrop (allow drag multi tree-table include all type: table, ol, ul) + * Demo: http://thienhung1989.github.io/angular-tree-dnd + * Github: https://github.com/thienhung1989/angular-tree-dnd + * @version 3.0.5 + * @preserve + * (c) 2015 Nguyuễn Thiện Hùng - + */ +(function () { + 'use strict'; + angular.isUndefinedOrNull = isUndefinedOrNull; + + angular.isDefined = isDefined; + + angular.module('ntt.TreeDnD', ['template/TreeDnD/TreeDnD.html']) + .constant( + '$TreeDnDClass', { + tree: 'tree-dnd', + empty: 'tree-dnd-empty', + hidden: 'tree-dnd-hidden', + node: 'tree-dnd-node', + nodes: 'tree-dnd-nodes', + handle: 'tree-dnd-handle', + place: 'tree-dnd-placeholder', + drag: 'tree-dnd-drag', + status: 'tree-dnd-status', + icon: { + '1': 'glyphicon glyphicon-minus', + '0': 'glyphicon glyphicon-plus', + '-1': 'glyphicon glyphicon-file' + } + } + );angular.module('ntt.TreeDnD') + .directive( + 'compile', [ + '$compile', function ($compile) { + return { + restrict: 'A', + link: function (scope, element, attrs) { + scope.$watch( + attrs.compile, function (new_val) { + if (new_val) { + if (angular.isFunction(element.empty)) { + element.empty(); + } else { + element.html(''); + } + + element.append($compile(new_val)(scope)); + } + } + ); + } + }; + }] +) + .directive( + 'compileReplace', [ + '$compile', function ($compile) { + return { + restrict: 'A', + link: function (scope, element, attrs) { + scope.$watch( + attrs.compileReplace, function (new_val) { + if (new_val) { + element.replaceWith($compile(new_val)(scope)); + } + } + ); + } + }; + }] +); + +angular.module('ntt.TreeDnD') .directive( 'treeDndNodeHandle', function () { return { restrict: 'A', scope: true, link: function (scope, element, attrs) { scope.$type = 'TreeDnDNodeHandle'; if (scope.$class.handle) { element.addClass(scope.$class.handle); } } }; } ); + +angular.module('ntt.TreeDnD') + .directive( + 'treeDndNode', ['$TreeDnDViewport', '$timeout', function ($TreeDnDViewport, $timeout) { + return { + restrict: 'A', + replace: true, + link: fnLink + }; + function fnLink(scope, element, attrs) { + + scope.$node_class = ''; + + if (scope.$class.node) { + element.addClass(scope.$class.node); + scope.$node_class = scope.$class.node; + } + var enabledDnD = typeof scope.dragEnabled === 'boolean' || typeof scope.dropEnabled === 'boolean', + keyNode = attrs.treeDndNode, + first = true, + childsElem; + //removeIf(nodebug) + console.log('Created Node'); + //endRemoveIf(nodebug) + $TreeDnDViewport.add(scope, element); + + if (enabledDnD) { + scope.$type = 'TreeDnDNode'; + + scope.getData = function () { + return scope[keyNode]; + }; + } + + scope.$element = element; + scope[keyNode].__inited__ = true; + + scope.getElementChilds = function () { + return angular.element(element[0].querySelector('[tree-dnd-nodes]')); + }; + + scope.setScope(scope, scope[keyNode]); + + scope.getScopeNode = function () { + return scope; + }; + + var objprops = [], + objexpr, + i, keyO = Object.keys(scope[keyNode]), + lenO = keyO.length, + hashKey = scope[keyNode].__hashKey__, + skipAttr = [ + '__visible__', + '__children__', + '__level__', + '__index__', + '__index_real__', + + '__parent__', + '__parent_real__', + '__dept__', + '__icon__', + '__icon_class__' + ], + keepAttr = [ + '__expanded__' + ], + lenKeep = keepAttr.length; + + // skip __visible__ + for (i = 0; i < lenO + lenKeep; i++) { + if (i < lenO) { + if (skipAttr.indexOf(keyO[i]) === -1) { + objprops.push(keyNode + '.' + keyO[i]); + } + } else { + if (keyO.indexOf(keepAttr[i - lenO]) === -1) { + objprops.push(keyNode + '.' + keepAttr[i - lenO]); + } + } + } + + objexpr = '[' + objprops.join(',') + ']'; + + scope.$watch(objexpr, fnWatchNode, true); + + scope.$on('$destroy', function () { + scope.deleteScope(scope, scope[keyNode]); + }); + + function fnWatchNode(newVal, oldVal, scope) { + + //removeIf(nodebug) + console.time('Node_Changed'); + //endRemoveIf(nodebug) + var nodeOf = scope[keyNode], + _icon; + + if (first) { + _icon = nodeOf.__icon__; + nodeOf.__icon_class__ = scope.$class.icon[_icon]; + } else { + + var parentReal = nodeOf.__parent_real__, + parentNode = scope.tree_nodes[parentReal] || null, + _childs = nodeOf.__children__, + _len = _childs.length, + _i; + + if (!nodeOf.__inited__) { + nodeOf.__inited__ = true; + } + + if (nodeOf.__hashKey__ !== hashKey) { + // clear scope in $globals + scope.deleteScope(scope, nodeOf); + + // add new scope into $globals + scope.setScope(scope, nodeOf); + hashKey = nodeOf.__hashKey__; + } + + if (parentNode && (!parentNode.__expanded__ || !parentNode.__visible__)) { + element.addClass(scope.$class.hidden); + nodeOf.__visible__ = false; + } else { + element.removeClass(scope.$class.hidden); + nodeOf.__visible__ = true; + } + + if (_len === 0) { + _icon = -1; + } else { + if (nodeOf.__expanded__) { + _icon = 1; + } else { + _icon = 0; + } + } + + nodeOf.__icon__ = _icon; + nodeOf.__icon_class__ = scope.$class.icon[_icon]; + + if (scope.isTable) { + for (_i = 0; _i < _len; _i++) { + scope.for_all_descendants(_childs[_i], scope.hiddenChild, nodeOf, true); + } + } else { + if (!childsElem) { + childsElem = scope.getElementChilds(); + } + + if (nodeOf.__expanded__) { + childsElem.removeClass(scope.$class.hidden); + } else { + childsElem.addClass(scope.$class.hidden); + } + } + + } + + //removeIf(nodebug) + console.timeEnd('Node_Changed'); + //endRemoveIf(nodebug) + first = false; + + } + } + }] +); + +angular.module('ntt.TreeDnD') + .directive( + 'treeDndNodes', function () { + return { + restrict: 'A', + replace: true, + link: function (scope, element/*, attrs*/) { + scope.$type = 'TreeDnDNodes'; + + if (scope.$class.nodes) { + element.addClass(scope.$class.nodes); + scope.$nodes_class = scope.$class.nodes; + } else { + scope.$nodes_class = ''; + } + } + }; + } +); + +angular.module('ntt.TreeDnD') + .directive( + 'treeDnd', fnInitTreeDnD); + +fnInitTreeDnD.$inject = [ + '$timeout', '$http', '$compile', '$parse', '$window', '$document', '$templateCache', + '$TreeDnDTemplate', '$TreeDnDClass', '$TreeDnDHelper', '$TreeDnDPlugin', '$TreeDnDViewport' +]; + +function fnInitTreeDnD($timeout, $http, $compile, $parse, $window, $document, $templateCache, + $TreeDnDTemplate, $TreeDnDClass, $TreeDnDHelper, $TreeDnDPlugin, $TreeDnDViewport +) { + return { + restrict: 'E', + scope: true, + replace: true, + controller: ['$scope', '$element', '$attrs', fnController], + compile: fnCompile + }; + + function fnController($scope, $element, $attrs) { + $scope.indent = 20; + $scope.indent_plus = 15; + $scope.indent_unit = 'px'; + $scope.$tree_class = 'table'; + $scope.primary_key = '__uid__'; + + $scope.$type = 'TreeDnD'; + // $scope.enabledFilter = null; + $scope.colDefinitions = []; + $scope.$globals = {}; + $scope.$class = {}; + + $scope.treeData = []; + $scope.tree_nodes = []; + + $scope.$class = angular.copy($TreeDnDClass); + angular.extend( + $scope.$class.icon, { + '1': $attrs.iconExpand || 'glyphicon glyphicon-minus', + '0': $attrs.iconCollapse || 'glyphicon glyphicon-plus', + '-1': $attrs.iconLeaf || 'glyphicon glyphicon-file' + } + ); + + $scope.for_all_descendants = function (node, fn, parent, checkSibling) { + if (angular.isFunction(fn)) { + var _i, _len, _nodes; + + if (fn(node, parent)) { + // have error or need ignore children + return false; + } + _nodes = node.__children__; + _len = _nodes ? _nodes.length : 0; + for (_i = 0; _i < _len; _i++) { + if (!$scope.for_all_descendants(_nodes[_i], fn, node) && !checkSibling) { + // skip sibling of node checking + return false; + } + } + } + // succeed then continue + return true; + }; + + $scope.getLastDescendant = function (node) { + var last_child, n; + if (!node) { + node = $scope.tree ? $scope.tree.selected_node : false; + } + if (node === false) { + return false; + } + n = node.__children__.length; + if (n === 0) { + return node; + } else { + last_child = node.__children__[n - 1]; + return $scope.getLastDescendant(last_child); + } + }; + + $scope.getElementChilds = function () { + return angular.element($element[0].querySelector('[tree-dnd-nodes]')); + }; + + $scope.onClick = function (node) { + if (angular.isDefined($scope.tree) && angular.isFunction($scope.tree.on_click)) { + // We want to detach from Angular's digest cycle so we can + // independently measure the time for one cycle. + setTimeout( + function () { + $scope.tree.on_click(node); + }, 0 + ); + } + }; + + $scope.onSelect = function (node) { + if (angular.isDefined($scope.tree)) { + if (node !== $scope.tree.selected_node) { + $scope.tree.select_node(node); + } + + if (angular.isFunction($scope.tree.on_select)) { + setTimeout( + function () { + $scope.tree.on_select(node); + }, 0 + ); + } + } + }; + + var passedExpand, _clone; + $scope.toggleExpand = function (node, fnCallback) { + passedExpand = true; + if (angular.isFunction(fnCallback) && !fnCallback(node)) { + passedExpand = false; + } else if (angular.isFunction($scope.$callbacks.expand) && !$scope.$callbacks.expand(node)) { + passedExpand = false; + } + + if (passedExpand) { + if (node.__children__.length > 0) { + node.__expanded__ = !node.__expanded__; + } + } + }; + + + var _fnGetHash = function (node) { + return '#' + node.__parent__ + '#' + node[$scope.primary_key]; + }, + _fnSetHash = function (node) { + var _hashKey = _fnGetHash(node); + if (angular.isUndefinedOrNull(node.__hashKey__) || node.__hashKey__ !== _hashKey) { + node.__hashKey__ = _hashKey; + } + return node; + }; + $scope.getHash = _fnGetHash; + $scope.$callbacks = { + getHash: _fnGetHash, + setHash: _fnSetHash, + for_all_descendants: $scope.for_all_descendants, + /*expand: function (node) { + return true; + },*/ + accept: function (dragInfo, moveTo, isChanged) { + return $scope.dropEnabled === true; + }, + calsIndent: function (level, skipUnit, skipEdge) { + var unit = 0, + edge = skipEdge ? 0 : $scope.indent_plus; + if (!skipUnit) { + unit = $scope.indent_unit ? $scope.indent_unit : 'px'; + } + + if (level - 1 < 1) { + return edge + unit; + } else { + return $scope.indent * (level - 1) + edge + unit; + } + }, + droppable: function () { + return $scope.dropEnabled === true; + }, + draggable: function () { + return $scope.dragEnabled === true; + }, + beforeDrop: function (event) { + return true; + }, + changeKey: function (node) { + var _key = node.__uid__; + node.__uid__ = Math.random(); + if (node.__selected__) { + delete node.__selected__; + } + + if ($scope.primary_key !== '__uid__') { + _key = '' + node[$scope.primary_key]; + _key = _key.replace(/_#.+$/g, '') + '_#' + node.__uid__; + + node[$scope.primary_key] = _key; + } + // delete(node.__hashKey__); + }, + clone: function (node, _this) { + _clone = angular.copy(node); + this.for_all_descendants(_clone, this.changeKey); + return _clone; + }, + remove: function (node, parent, _this, delayReload) { + var temp = parent.splice(node.__index__, 1)[0]; + if (!delayReload) { + $scope.reload_data(); + } + return temp; + }, + clearInfo: function (node) { + delete node.__inited__; + delete node.__visible__; + + // always changed after call reload_data + //delete node.__hashKey__; + }, + add: function (node, pos, parent, _this) { + // clearInfo + this.for_all_descendants(node, this.clearInfo); + if (parent) { + if (parent.length > -1) { + if (pos > -1) { + parent.splice(pos, 0, node); + } else { + // todo If children need load crazy + parent.push(node); + } + } else { + parent.push(node); + } + } + } + }; + + $scope.deleteScope = function (scope, node) { + var _hash = node.__hashKey__; + if ($scope.$globals[_hash] && $scope.$globals[_hash] === scope) { + delete $scope.$globals[_hash]; + } + }; + + $scope.setScope = function (scope, node) { + var _hash = node.__hashKey__; + if ($scope.$globals[_hash] !== scope) { + $scope.$globals[_hash] = scope; + } + }; + + $scope.getScope = function (node) { + if (node) { + var _hash = node.__hashKey__; + //var _hash = typeof node === 'string' ? node : node.__hashKey__; + return $scope.$globals[_hash]; + } + return $scope; + }; + + if ($attrs.enableDrag || $attrs.enableDrop) { + $scope.placeElm = null; + // $scope.dragBorder = 30; + $scope.dragEnabled = null; + $scope.dropEnabled = null; + $scope.horizontal = null; + + if ($attrs.enableDrag) { + + $scope.dragDelay = 0; + $scope.enabledMove = true; + $scope.statusMove = true; + $scope.enabledHotkey = false; + $scope.enabledCollapse = null; + $scope.statusElm = null; + $scope.dragging = null; + + angular.extend( + $scope.$callbacks, { + beforeDrag: function (scopeDrag) { + return true; + }, + dragStop: function (info, passed) { + if (!info || !info.changed && info.drag.enabledMove || !passed) { + return null; + } + + info.target.reload_data(); + + if (info.target !== info.drag && info.drag.enabledMove) { + info.drag.reload_data(); + } + }, + dropped: function (info, pass) { + if (!info) { + return null; + } + + var _node = info.node, + _nodeAdd = null, + _move = info.move, + _parent = null, + _parentRemove = info.parent || info.drag.treeData, + _parentAdd = _move.parent || info.target.treeData, + isMove = info.drag.enabledMove; + + if (!info.changed && isMove) { + return false; + } + + if (info.target.$callbacks.accept(info, info.move, info.changed)) { + if (isMove) { + _parent = _parentRemove; + if (angular.isDefined(_parent.__children__)) { + _parent = _parent.__children__; + } + + _nodeAdd = info.drag.$callbacks.remove( + _node, + _parent, + info.drag.$callbacks, + true // delay reload + ); + } else { + _nodeAdd = info.drag.$callbacks.clone(_node, info.drag.$callbacks); + } + + // if node dragging change index in sample node parent + // and index node decrement + if (isMove && + info.drag === info.target && + _parentRemove === _parentAdd && + _move.pos >= info.node.__index__) { + _move.pos--; + } + + _parent = _parentAdd; + if (_parent.__children__) { + _parent = _parent.__children__; + } + + info.target.$callbacks.add( + _nodeAdd, + _move.pos, + _parent, + info.drag.$callbacks + ); + + return true; + } + + return false; + }, + dragStart: function (event) { + }, + dragMove: function (event) { + } + } + ); + + $scope.setDragging = function (dragInfo) { + $scope.dragging = dragInfo; + }; + + $scope.enableMove = function (val) { + if (typeof val === 'boolean') { + $scope.enabledMove = val; + } else { + $scope.enabledMove = true; + } + }; + + if ($attrs.enableStatus) { + $scope.enabledStatus = false; + + $scope.hideStatus = function () { + if ($scope.statusElm) { + $scope.statusElm.addClass($scope.$class.hidden); + } + }; + + $scope.refreshStatus = function () { + if (!$scope.dragging) { + return; + } + + if ($scope.enabledStatus) { + var statusElmOld = $scope.statusElm; + if ($scope.enabledMove) { + $scope.statusElm = angular.element($TreeDnDTemplate.getMove($scope)); + } else { + $scope.statusElm = angular.element($TreeDnDTemplate.getCopy($scope)); + } + + if (statusElmOld !== $scope.statusElm) { + if (statusElmOld) { + $scope.statusElm.attr('class', statusElmOld.attr('class')); + $scope.statusElm.attr('style', statusElmOld.attr('style')); + statusElmOld.remove(); + } + $document.find('body').append($scope.statusElm); + + } + + $scope.statusElm.removeClass($scope.$class.hidden); + } + }; + + $scope.setPositionStatus = function (e) { + if ($scope.statusElm) { + $scope.statusElm.css( + { + 'left': e.pageX + 10 + 'px', + 'top': e.pageY + 15 + 'px', + 'z-index': 9999 + } + ); + $scope.statusElm.addClass($scope.$class.status); + } + }; + } + } + + $scope.targeting = false; + + $scope.getPrevSibling = function (node) { + if (node && node.__index__ > 0) { + var _parent, _index = node.__index__ - 1; + + if (angular.isDefined(node.__parent_real__)) { + _parent = $scope.tree_nodes[node.__parent_real__]; + return _parent.__children__[_index]; + } + return $scope.treeData[_index]; + + } + return null; + }; + + $scope.getNode = function (index) { + if (angular.isUndefinedOrNull(index)) { + return null; + } + return $scope.tree_nodes[index]; + }; + + $scope.initPlace = function (element, dragElm) { + + if (!$scope.placeElm) { + if ($scope.isTable) { + $scope.placeElm = angular.element($window.document.createElement('tr')); + var _len_down = $scope.colDefinitions.length; + $scope.placeElm.append( + angular.element($window.document.createElement('td')) + .addClass($scope.$class.empty) + .addClass('indented') + .addClass($scope.$class.place) + ); + while (_len_down-- > 0) { + $scope.placeElm.append( + angular.element($window.document.createElement('td')) + .addClass($scope.$class.empty) + .addClass($scope.$class.place) + ); + } + } else { + $scope.placeElm = angular.element($window.document.createElement('li')) + .addClass($scope.$class.empty) + .addClass($scope.$class.place); + } + + } + + if (dragElm) { + $scope.placeElm.css('height', $TreeDnDHelper.height(dragElm) + 'px'); + } + + if (element) { + element[0].parentNode.insertBefore($scope.placeElm[0], element[0]); + } else { + $scope.getElementChilds().append($scope.placeElm); + } + + return $scope.placeElm; + }; + + $scope.hidePlace = function () { + if ($scope.placeElm) { + $scope.placeElm.addClass($scope.$class.hidden); + } + }; + + $scope.showPlace = function () { + if ($scope.placeElm) { + $scope.placeElm.removeClass($scope.$class.hidden); + } + }; + + $scope.getScopeTree = function () { + return $scope; + }; + + } + + $scope.$safeApply = $safeApply; + + + $scope.hiddenChild = function fnHiddenChild(node, parent) { + var nodeScope = $scope.getScope(node); + if (nodeScope) { + if (parent && parent.__expanded__ && parent.__visible__) { + nodeScope.$element.removeClass($scope.$class.hidden); + node.__visible__ = true; + } else { + nodeScope.$element.addClass($scope.$class.hidden); + node.__visible__ = false; + } + } else { + // show node & init scope + if (parent && parent.__expanded__ && parent.__visible__) { + node.__visible__ = true; + } else { + node.__visible__ = false; + } + } + + // skip all child hiding... if not expaned + return node.__expanded__ === false; + } + var _fnInitFilter, + _fnInitOrderBy, + _fnGetControl, + _defaultFilterOption = { + showParent: true, + showChild: false, + beginAnd: true + }, + tree, + _watches = [ + [ + 'enableDrag', [ + ['boolean', 'enableStatus', null, 'enabledStatus'], + ['boolean', 'enableMove', null, 'enabledMove'], + ['number', 'dragDelay', 0, null, 0], + ['boolean', 'enableCollapse', null, 'enabledCollapse'], + [ + 'boolean', 'enableHotkey', null, 'enabledHotkey', null, function (isHotkey) { + if (isHotkey) { + $scope.enabledMove = false; + } else { + $scope.enabledMove = $scope.statusMove; + } + }] + ]], + [ + ['enableDrag', 'enableStatus'], [ + [ + 'string', 'templateCopy', $attrs.templateCopy, 'templateCopy', null, + function (_url) { + if (_url && $templateCache.get(_url)) { + $TreeDnDTemplate.setCopy(_url, $scope); + } + }], + [ + 'string', 'templateMove', $attrs.templateMove, 'templateMove', null, + function (_url) { + if (_url && $templateCache.get(_url)) { + $TreeDnDTemplate.setMove(_url, $scope); + } + }] + ]], + [ + [['enableDrag', 'enableDrop']], [ + ['number', 'dragBorder', 30, 'dragBorder', 30]] + ], + [ + '*', [ + ['boolean', 'treeTable', true, 'treeTable', null], + ['boolean', 'horizontal'], + [ + 'callback', 'treeClass', function (val) { + switch (typeof val) { + case 'string': + $scope.$tree_class = val; + break; + case 'object': + angular.extend($scope.$class, val); + $scope.$tree_class = $scope.$class.tree; + break; + default: + $scope.$tree_class = $attrs.treeClass; + break; + } + }, 'treeClass', function () { + $scope.$tree_class = $scope.$class.tree + ' table'; + }, null, function () { + if (/^(\s+[\w\-]+){2,}$/g.test(' ' + $attrs.treeClass)) { + $scope.$tree_class = $attrs.treeClass.trim(); + return true; + } + }], + [ + ['object', 'string'], 'expandOn', getExpandOn, 'expandingProperty', getExpandOn, + function (expandOn) { + if (angular.isUndefinedOrNull(expandOn)) { + $scope.expandingProperty = $attrs.expandOn; + } + }], + [ + 'object', 'treeControl', angular.isDefined($scope.tree) ? $scope.tree : {}, + 'tree', null, function ($tree) { + + if (!angular.isFunction(_fnGetControl)) { + _fnGetControl = $TreeDnDPlugin('$TreeDnDControl'); + } + + if (angular.isFunction(_fnGetControl)) { + tree = angular.extend( + $tree, + _fnGetControl($scope) + ); + } + }], + [ + ['array', 'object'], 'columnDefs', getColDefs, 'colDefinitions', getColDefs, + function (colDefs) { + if (angular.isUndefinedOrNull(colDefs) || !angular.isArray(colDefs)) { + $scope.colDefinitions = getColDefs(); + } + }], + [['object', 'string', 'array', 'function'], 'orderBy', $attrs.orderBy], + [ + ['object', 'array'], 'filter', null, 'filter', null, function (filters) { + var _passed = false; + if (angular.isDefined(filters) && !angular.isArray(filters)) { + var _keysF = Object.keys(filters), + _lenF = _keysF.length, _iF; + + if (_lenF > 0) { + for (_iF = 0; _iF < _lenF; _iF++) { + + if (typeof filters[_keysF[_iF]] === 'string' && + filters[_keysF[_iF]].length === 0) { + continue; + } + _passed = true; + break; + } + } + } + + $scope.enabledFilter = _passed; + reload_data(); + }], + [ + 'object', 'filterOptions', _defaultFilterOption, 'filterOptions', + _defaultFilterOption, function (option) { + if (typeof option === 'object') { + $scope.filterOptions = angular.extend(_defaultFilterOption, option); + } + }], + ['string', 'primaryKey', $attrs.primaryKey, 'primary_key', '__uid__'], + ['string', 'indentUnit', $attrs.indentUnit, 'indent_unit'], + ['number', 'indent', 30, null, 30], + ['number', 'indentPlus', 20, null, 20], + [ + 'null', 'callbacks', + function (optCallbacks) { + angular.forEach( + optCallbacks, function (value, key) { + if (typeof value === 'function') { + if ($scope.$callbacks[key]) { + $scope.$callbacks[key] = value; + } + } + } + ); + return $scope.$callbacks; + }, + '$callbacks' + ], + [ + 'number', 'expandLevel', 3, 'expandLevel', 3, function () { + reload_data(); + }], + ['number', 'treeLimit', 100, '$TreeLimit', 100], + ['boolean', 'enableDrag', null, 'dragEnabled'], + ['boolean', 'enableDrop', null, 'dropEnabled'] + ]] + ], + w, lenW = _watches.length, + i, len, + _curW, + _typeW, _nameW, _defaultW, _scopeW, _NotW, _AfterW, _BeforeW, + + // debounce reload_Data; + timeReloadData, tmpTreeData; + + for (w = 0; w < lenW; w++) { + // skip if not exist + if (!check_exist_attr($attrs, _watches[w][0], true)) { + continue; + } + _curW = _watches[w][1]; + for (i = 0, len = _curW.length; i < len; i++) { + _typeW = _curW[i][0]; + _nameW = _curW[i][1]; + _defaultW = _curW[i][2]; + _scopeW = _curW[i][3]; + _NotW = _curW[i][4]; + _AfterW = _curW[i][5]; + _BeforeW = _curW[i][6]; + generateWatch(_typeW, _nameW, _defaultW, _scopeW, _NotW, _AfterW, _BeforeW); + } + } + + if ($attrs.treeData) { + $scope.$watch( + $attrs.treeData, function (val) { + if (angular.equals(val, $scope.treeData)) { + return; + } + + tmpTreeData = val; + if (angular.isUndefinedOrNull(timeReloadData)) { + timeReloadData = $timeout(timeLoadData, 350); + } + }, true + ); + } + + function timeLoadData() { + $scope.treeData = tmpTreeData; + reload_data(); + timeReloadData = null; + } + + $scope.updateLimit = function updateLimit() { + //console.log('Call fn UpdateLimit'); + $scope.$TreeLimit += 50; + }; + + $scope.reload_data = reload_data; + + function check_exist_attr(attrs, existAttr, isAnd) { + if (angular.isUndefinedOrNull(existAttr)) { + return false; + } + + if (existAttr === '*' || !angular.isUndefined(attrs[existAttr])) { + return true; + } + + if (angular.isArray(existAttr)) { + return for_each_attrs(attrs, existAttr, isAnd); + } + } + + function for_each_attrs(attrs, exist, isAnd) { + var i, len = exist.length, passed = false; + + if (len === 0) { + return null; + } + for (i = 0; i < len; i++) { + if (check_exist_attr(attrs, exist[i], !isAnd)) { + passed = true; + if (!isAnd) { + return true; + } + } else { + if (isAnd) { + return false; + } + } + } + + return passed; + } + + function generateWatch(type, nameAttr, valDefault, nameScope, fnNotExist, fnAfter, + fnBefore + ) { + nameScope = nameScope || nameAttr; + if (typeof type === 'string' || angular.isArray(type)) { + if (angular.isFunction(fnBefore) && fnBefore()) { + return;//jmp + } + if (typeof $attrs[nameAttr] === 'string') { + $scope.$watch( + $attrs[nameAttr], function (val) { + if (typeof type === 'string' && typeof val === type || + angular.isArray(type) && type.indexOf(typeof val) > -1 + ) { + $scope[nameScope] = val; + } else { + if (angular.isFunction(valDefault)) { + $scope[nameScope] = valDefault(val); + } else { + $scope[nameScope] = valDefault; + } + } + + if (angular.isFunction(fnAfter)) { + fnAfter($scope[nameScope], $scope); + } + }, true + ); + } else { + + if (angular.isFunction(fnNotExist)) { + $scope[nameScope] = fnNotExist(); + } else if (!angular.isUndefined(fnNotExist)) { + $scope[nameScope] = fnNotExist; + } + } + } + } + + function $safeApply(fn) { + var phase = this.$root.$$phase; + if (phase === '$apply' || phase === '$digest') { + if (fn && typeof fn === 'function') { + fn(); + } + } else { + this.$apply(fn); + } + } + + function getExpandOn() { + if ($scope.treeData && $scope.treeData.length) { + var _firstNode = $scope.treeData[0], _keys = Object.keys(_firstNode), + _regex = new RegExp('^__([a-zA-Z0-9_\-]*)__$'), + _len, + i; + // Auto get first field with type is string; + for (i = 0, _len = _keys.length; i < _len; i++) { + if (typeof _firstNode[_keys[i]] === 'string' && !_regex.test(_keys[i])) { + $scope.expandingProperty = _keys[i]; + return; + } + } + + // Auto get first + if (angular.isUndefinedOrNull($scope.expandingProperty)) { + $scope.expandingProperty = _keys[0]; + } + + } + } + + function getColDefs() { + // Auto get Defs except attribute __level__ .... + if ($scope.treeData.length) { + var _col_defs = [], _firstNode = $scope.treeData[0], + _regex = new RegExp('(^__([a-zA-Z0-9_\-]*)__$|^' + $scope.expandingProperty + '$)'), + _keys = Object.keys(_firstNode), + i, _len; + // Auto get first field with type is string; + for (i = 0, _len = _keys.length; i < _len; i++) { + if (typeof _firstNode[_keys[i]] === 'string' && !_regex.test(_keys[i])) { + _col_defs.push( + { + field: _keys[i] + } + ); + } + } + $scope.colDefinitions = _col_defs; + } + } + + function do_f(root, node, parent, parent_real, level, visible, index) { + + if(typeof node !== 'object'){ + return 0; + } + + var _i, _len, _icon, _index_real, _dept, _hashKey; + if (!angular.isArray(node.__children__)) { + node.__children__ = []; + } + + node.__parent_real__ = parent_real; + node.__parent__ = parent; + _len = node.__children__.length; + + if (angular.isUndefinedOrNull(node.__expanded__) && _len > 0) { + node.__expanded__ = level < $scope.expandLevel; + } + + if (_len === 0) { + _icon = -1; + } else { + if (node.__expanded__) { + _icon = 1; + } else { + _icon = 0; + } + } + + // Insert item vertically + _index_real = root.length; + node.__index__ = index; + node.__index_real__ = _index_real; + node.__level__ = level; + node.__icon__ = _icon; + node.__icon_class__ = $scope.$class.icon[_icon]; + node.__visible__ = !!visible; + + if (angular.isUndefinedOrNull(node.__uid__)) { + node.__uid__ = '' + Math.random(); + } + + _hashKey = $scope.getHash(node); + + if (angular.isUndefinedOrNull(node.__hashKey__) || node.__hashKey__ !== _hashKey) { + node.__hashKey__ = _hashKey; + } + + root.push(node); + + // Check node children + _dept = 1; + if (_len > 0) { + for (_i = 0; _i < _len; _i++) { + _dept += do_f( + root, + node.__children__[_i], + node[$scope.primary_key], + _index_real, + level + 1, + visible && node.__expanded__, + _i + ); + } + } + + node.__dept__ = _dept; + + return _dept; + } + + function init_data(data) { + + // clear memory + if (angular.isDefined($scope.tree_nodes)) { + delete $scope.tree_nodes; + } + + $scope.tree_nodes = data; + return data; + } + + function reload_data(oData) { + //removeIf(nodebug) + console.time('Reload_Data'); + //endRemoveIf(nodebug) + + var _data, + _len, + _tree_nodes = []; + if (angular.isDefined(oData)) { + if (!angular.isArray(oData) || oData.length === 0) { + return init_data([]); + } else { + _data = oData; + } + } else if (!angular.isArray($scope.treeData) || $scope.treeData.length === 0) { + return init_data([]); + } else { + _data = $scope.treeData; + } + + if (!$attrs.expandOn) { + getExpandOn(); + } + + if (!$attrs.columnDefs) { + getColDefs(); + } + + if (angular.isDefined($scope.orderBy)) { + if (!angular.isFunction(_fnInitOrderBy)) { + _fnInitOrderBy = $TreeDnDPlugin('$TreeDnDOrderBy'); + } + + if (angular.isFunction(_fnInitOrderBy)) { + _data = _fnInitOrderBy(_data, $scope.orderBy); + } + } + + if (angular.isDefined($scope.filter)) { + if (!angular.isFunction(_fnInitFilter)) { + _fnInitFilter = $TreeDnDPlugin('$TreeDnDFilter'); + } + + if (angular.isFunction(_fnInitFilter)) { + _data = _fnInitFilter(_data, $scope.filter, $scope.filterOptions); + } + } + + _len = _data.length; + if (_len > 0) { + var _i, + _deptTotal = 0; + + for (_i = 0; _i < _len; _i++) { + _deptTotal += do_f(_tree_nodes, _data[_i], null, null, 1, true, _i); + } + + } + + init_data(_tree_nodes); + + //removeIf(nodebug) + console.timeEnd('Reload_Data'); + //endRemoveIf(nodebug) + return _tree_nodes; + } + } + + function fnCompile(tElement) { + + var $_Template = '', + _element = tElement.html().trim(); + + if (_element.length > 0) { + $_Template = _element; + tElement.html(''); + } + + return function fnPost(scope, element, attrs) { + + if (attrs.enableDrag) { + var _fnInitDrag = $TreeDnDPlugin('$TreeDnDDrag'); + if (angular.isFunction(_fnInitDrag)) { + _fnInitDrag(scope, element, $window, $document); + } + } + + // kick out $digest + element.ready(function () { + // apply Template + function checkTreeTable(template, scope) { + var elemNode = template[0].querySelector('[tree-dnd-node]'), + attrInclude; + + scope.isTable = null; + if (elemNode) { + elemNode = angular.element(elemNode); + attrInclude = elemNode.attr('ng-include'); + } else { + return; + } + + if (attrInclude) { + var treeInclude = $parse(attrInclude)(scope) || attrInclude; + if (typeof treeInclude === 'string') { + return $http.get( + treeInclude, + {cache: $templateCache} + ).success( + function (data) { + data = data.trim(); + //scope.templateNode = data; + var tempDiv = document.createElement('div'); + tempDiv.innerHTML = data; + tempDiv = angular.element(tempDiv); + scope.isTable = !tempDiv[0].querySelector('[tree-dnd-nodes]'); + } + ); + } + } else { + scope.isTable = !elemNode[0].querySelector('[tree-dnd-nodes]'); + //scope.templateNode = elemNode.html(); + } + $TreeDnDViewport.setTemplate(scope, scope.templateNode); + //elemNode.html(''); + } + + //scope.$watch(tableDataLoaded, transformTable); + /* + function tableDataLoaded(elem) { + // first cell in the tbody exists when data is loaded but doesn't have a width + // until after the table is transformed + var firstCell = elem.querySelector('tbody tr:first-child td:first-child'); + return firstCell && !firstCell.style.width; + } + + function transformTable(elem, attrs) { + // reset display styles so column widths are correct when measured below + angular.element(elem.querySelectorAll('thead, tbody, tfoot')).css('display', ''); + + // wrap in $timeout to give table a chance to finish rendering + $timeout(function () { + // set widths of columns + angular.forEach(elem.querySelectorAll('tr:first-child th'), function (thElem, i) { + + var tdElems = elem.querySelector('tbody tr:first-child td:nth-child(' + (i + 1) + ')'); + var tfElems = elem.querySelector('tfoot tr:first-child td:nth-child(' + (i + 1) + ')'); + + var columnWidth = tdElems ? tdElems.offsetWidth : thElem.offsetWidth; + if (tdElems) { + tdElems.style.width = columnWidth + 'px'; + } + if (thElem) { + thElem.style.width = columnWidth + 'px'; + } + if (tfElems) { + tfElems.style.width = columnWidth + 'px'; + } + }); + + // set css styles on thead and tbody + angular.element(elem.querySelectorAll('thead, tfoot')).css('display', 'block'); + + angular.element(elem.querySelectorAll('tbody')).css({ + 'display': 'block', + 'height': attrs.tableHeight || 'inherit', + 'overflow': 'auto' + }); + + // reduce width of last column by width of scrollbar + var tbody = elem.querySelector('tbody'); + var scrollBarWidth = tbody.offsetWidth - tbody.clientWidth; + if (scrollBarWidth > 0) { + // for some reason trimming the width by 2px lines everything up better + scrollBarWidth -= 2; + var lastColumn = elem.querySelector('tbody tr:first-child td:last-child'); + lastColumn.style.width = lastColumn.offsetWidth - scrollBarWidth + 'px'; + } + }); + }*/ + var promiseCheck; + if ($_Template.length > 0) { + promiseCheck = checkTreeTable(angular.element($_Template.trim()), scope); + if (typeof promiseCheck === 'object') { + promiseCheck.then(function () { + element.append($compile($_Template)(scope)); + }); + } else { + element.append($compile($_Template)(scope)); + } + } else { + $http.get( + attrs.templateUrl || $TreeDnDTemplate.getPath(), + {cache: $templateCache} + ).success( + function (data) { + data = angular.element(data.trim()); + promiseCheck = checkTreeTable(data, scope); + if (typeof promiseCheck === 'object') { + promiseCheck.then(function () { + element.append($compile(data)(scope)); + }); + } else { + element.append($compile(data)(scope)); + } + } + ); + } + }) + }; + } +} + + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDFilter', [ + '$filter', function ($filter) { + return fnInitFilter; + + function for_all_descendants(options, node, fieldChild, fnBefore, fnAfter, parentPassed) { + if (!angular.isFunction(fnBefore)) { + return null; + } + + var _i, _len, _nodes, + _nodePassed = fnBefore(options, node), + _childPassed = false, + _filter_index = options.filter_index; + + if (angular.isDefined(node[fieldChild])) { + _nodes = node[fieldChild]; + _len = _nodes.length; + options.filter_index = 0; + for (_i = 0; _i < _len; _i++) { + _childPassed = for_all_descendants( + options, + _nodes[_i], + fieldChild, + fnBefore, + fnAfter, + _nodePassed || parentPassed + ) || _childPassed; + } + + // restore filter_index of node + options.filter_index = _filter_index; + } + + if (angular.isFunction(fnAfter)) { + fnAfter(options, node, _nodePassed === true, _childPassed === true, parentPassed === true); + } + + return _nodePassed || _childPassed; + } + + /** + * Check data with callback + * @param {string|object|function|regex} callback + * @param {*} data + * @returns {null|boolean} + * @private + */ + function _fnCheck(callback, data) { + if (angular.isUndefinedOrNull(data) || angular.isArray(data)) { + return null; + } + + if (angular.isFunction(callback)) { + return callback(data, $filter); + } else { + if (typeof callback === 'boolean') { + data = !!data; + return data === callback; + } else if (angular.isDefined(callback)) { + try { + var _regex = new RegExp(callback); + return _regex.test(data); + } + catch (err) { + if (typeof data === 'string') { + return data.indexOf(callback) > -1; + } else { + return null; + } + } + } else { + return null; + } + } + } + + /** + * `fnProcess` to call `_fnCheck`. If `condition` is `array` then call `for_each_filter` + * else will call `_fnCheck`. Specical `condition.field` is `_$` then apply `condition.callback` for all field, if have `field` invaild then `return true`. + * + * @param node + * @param condition + * @param isAnd + * @returns {null|boolean} + * @private + */ + function _fnProccess(node, condition, isAnd) { + if (angular.isArray(condition)) { + return for_each_filter(node, condition, isAnd); + } else { + var _key = condition.field, + _callback = condition.callback, + _iO, _keysO, _lenO; + + if (_key === '_$') { + _keysO = Object.keys(node); + _lenO = _keysO.length; + for (_iO = 0; _iO < _lenO; _iO++) { + if (_fnCheck(_callback, node[_keysO[_iO]])) { + return true; + } + } + } else if (angular.isDefined(node[_key])) { + return _fnCheck(_callback, node[_key]); + } + } + return null; + } + + /** + * + * @param {object} node + * @param {array} conditions Array `conditions` + * @param {boolean} isAnd check with condition `And`, if `And` then `return false` when all `false` + * @returns {null|boolean} + */ + function for_each_filter(node, conditions, isAnd) { + var i, len = conditions.length || 0, passed = false; + if (len === 0) { + return null; + } + + for (i = 0; i < len; i++) { + if (_fnProccess(node, conditions[i], !isAnd)) { + passed = true; + // if condition `or` then return; + if (!isAnd) { + return true; + } + } else { + + // if condition `and` and result in fnProccess = false then return; + if (isAnd) { + return false; + } + } + } + + return passed; + } + + /** + * Will call _fnAfter to clear data no need + * @param {object} options + * @param {object} node + * @param {boolean} isNodePassed + * @param {boolean} isChildPassed + * @param {boolean} isParentPassed + * @private + */ + function _fnAfter(options, node, isNodePassed, isChildPassed, isParentPassed) { + if (isNodePassed === true) { + node.__filtered__ = true; + node.__filtered_visible__ = true; + node.__filtered_index__ = options.filter_index++; + return; //jmp + } else if (isChildPassed === true && options.showParent === true + || isParentPassed === true && options.showChild === true) { + node.__filtered__ = false; + node.__filtered_visible__ = true; + node.__filtered_index__ = options.filter_index++; + return; //jmp + } + + // remove attr __filtered__ + delete node.__filtered__; + delete node.__filtered_visible__; + delete node.__filtered_index__; + } + + /** + * `fnBefore` will called when `for_all_descendants` of `node` checking. + * If `filter` empty then return `true` else result of function `_fnProccess` {@see _fnProccess} + * + * @param {object} options + * @param {object} node + * @returns {null|boolean} + * @private + */ + function _fnBefore(options, node) { + if (options.filter.length === 0) { + return true; + } else { + return _fnProccess(node, options.filter, options.beginAnd || false); + } + } + + /** + * `fnBeforeClear` will called when `for_all_descendants` of `node` checking. + * Alway false to Clear Filter empty + * + * @param {object} options + * @param {object} node + * @returns {null|boolean} + * @private + */ + function _fnBeforeClear(options, node) { + return false; + } + + /** + * `_fnConvert` to convert `filter` `object` to `array` invaild. + * + * @param {object|array} filters + * @returns {array} Instead of `filter` or new array invaild *(converted from filter)* + * @private + */ + function _fnConvert(filters) { + var _iF, _lenF, _keysF, + _filter, + _state; + // convert filter object to array filter + if (angular.isObject(filters) && !angular.isArray(filters)) { + _keysF = Object.keys(filters); + _lenF = _keysF.length; + _filter = []; + + if (_lenF > 0) { + for (_iF = 0; _iF < _lenF; _iF++) { + + if (typeof filters[_keysF[_iF]] === 'string' && filters[_keysF[_iF]].length === 0) { + continue; + } else if (angular.isArray(filters[_keysF[_iF]])) { + _state = filters[_keysF[_iF]]; + } else if (angular.isObject(filters[_keysF[_iF]])) { + _state = _fnConvert(filters[_keysF[_iF]]); + } else { + _state = { + field: _keysF[_iF], + callback: filters[_keysF[_iF]] + }; + } + _filter.push(_state); + } + } + _state = null; + return _filter; + } + else { + return filters; + } + } + + /** + * `fnInitFilter` function is constructor of service `$TreeDnDFilter`. + * @constructor + * @param {object|array} treeData + * @param {object|array} filters + * @param {object} options + * @param {string} keyChild + * @returns {array} Return `treeData` or `treeData` with `filter` + * @private + */ + function fnInitFilter(treeData, filters, options, keyChild) { + if (!angular.isArray(treeData) + || treeData.length === 0) { + return treeData; + } + + var _i, _len, + _filter; + + _filter = _fnConvert(filters); + if (!(angular.isArray(_filter) || angular.isObject(_filter)) + || _filter.length === 0) { + for (_i = 0, _len = treeData.length; _i < _len; _i++) { + for_all_descendants( + options, + treeData[_i], + keyChild || '__children__', + _fnBeforeClear, _fnAfter + ); + } + return treeData; + } + + options.filter = _filter; + options.filter_index = 0; + for (_i = 0, _len = treeData.length; _i < _len; _i++) { + for_all_descendants( + options, + treeData[_i], + keyChild || '__children__', + _fnBefore, _fnAfter + ); + } + + return treeData; + } + + }] +); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDOrderBy', [ + '$filter', function ($filter) { + var _fnOrderBy = $filter('orderBy'), + for_all_descendants = function for_all_descendants(options, node, name, fnOrderBy) { + var _i, _len, _nodes; + + if (angular.isDefined(node[name])) { + _nodes = node[name]; + _len = _nodes.length; + // OrderBy children + for (_i = 0; _i < _len; _i++) { + _nodes[_i] = for_all_descendants(options, _nodes[_i], name, fnOrderBy); + } + + node[name] = fnOrderBy(node[name], options); + } + return node; + }, + _fnOrder = function _fnOrder(list, orderBy) { + return _fnOrderBy(list, orderBy); + }, + _fnMain = function _fnMain(treeData, orderBy) { + if (!angular.isArray(treeData) + || treeData.length === 0 + || !(angular.isArray(orderBy) || angular.isObject(orderBy) || angular.isString(orderBy) || angular.isFunction(orderBy)) + || orderBy.length === 0 && !angular.isFunction(orderBy)) { + return treeData; + } + + var _i, _len; + + for (_i = 0, _len = treeData.length; _i < _len; _i++) { + treeData[_i] = for_all_descendants( + orderBy, + treeData[_i], + '__children__', + _fnOrder + ); + } + + return _fnOrder(treeData, orderBy); + }; + + return _fnMain; + }] +); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDConvert', function () { + var _$initConvert = { + line2tree: function (data, primaryKey, parentKey, callback) { + callback = typeof callback === 'function' ? callback : function () { + }; + if (!data || data.length === 0 || !primaryKey || !parentKey) { + return []; + } + var tree = [], + rootIds = [], + item = data[0], + _primary = item[primaryKey], + treeObjs = {}, + parentId, parent, + len = data.length, + i = 0; + while (i < len) { + item = data[i++]; + callback(item); + _primary = item[primaryKey]; + treeObjs[_primary] = item; + } + i = 0; + while (i < len) { + item = data[i++]; + callback(item); + _primary = item[primaryKey]; + treeObjs[_primary] = item; + parentId = item[parentKey]; + if (parentId) { + parent = treeObjs[parentId]; + if (parent) { + if (parent.__children__) { + parent.__children__.push(item); + } else { + parent.__children__ = [item]; + } + } + } else { + rootIds.push(_primary); + } + } + len = rootIds.length; + for (i = 0; i < len; i++) { + tree.push(treeObjs[rootIds[i]]); + } + return tree; + }, + tree2tree: function access_child(data, containKey, callback) { + callback = typeof callback === 'function' ? callback : function () { + }; + var _tree = [], + _i, + _len = data ? data.length : 0, + _copy, _child; + for (_i = 0; _i < _len; _i++) { + _copy = angular.copy(data[_i]); + callback(_copy); + if (angular.isArray(_copy[containKey]) && _copy[containKey].length > 0) { + _child = access_child(_copy[containKey], containKey, callback); + delete _copy[containKey]; + _copy.__children__ = _child; + } + _tree.push(_copy); + } + return _tree; + } + }; + + return _$initConvert; + } + ); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDHelper', [ + '$document', '$window', function ($document, $window) { + var _$helper = { + nodrag: function (targetElm) { + return typeof targetElm.attr('data-nodrag') !== 'undefined'; + }, + eventObj: function (e) { + var obj = e; + if (e.targetTouches !== undefined) { + obj = e.targetTouches.item(0); + } else if (e.originalEvent !== undefined && e.originalEvent.targetTouches !== undefined) { + obj = e.originalEvent.targetTouches.item(0); + } + return obj; + }, + dragInfo: function (scope) { + var _node = scope.getData(), + _tree = scope.getScopeTree(), + _parent = scope.getNode(_node.__parent_real__); + return { + node: _node, + parent: _parent, + move: { + parent: _parent, + pos: _node.__index__ + }, + scope: scope, + target: _tree, + drag: _tree, + drop: scope.getPrevSibling(_node), + changed: false + }; + }, + height: function (element) { + return element.prop('scrollHeight'); + }, + width: function (element) { + return element.prop('scrollWidth'); + }, + offset: function (element) { + var boundingClientRect = element[0].getBoundingClientRect(); + return { + width: element.prop('offsetWidth'), + height: element.prop('offsetHeight'), + top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop), + left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft) + }; + }, + positionStarted: function (e, target) { + var pos = {}; + pos.offsetX = e.pageX - this.offset(target).left; + pos.offsetY = e.pageY - this.offset(target).top; + pos.startX = pos.lastX = e.pageX; + pos.startY = pos.lastY = e.pageY; + pos.nowX = pos.nowY = pos.distX = pos.distY = pos.dirAx = 0; + pos.dirX = pos.dirY = pos.lastDirX = pos.lastDirY = pos.distAxX = pos.distAxY = 0; + return pos; + }, + positionMoved: function (e, pos, firstMoving) { + // mouse position last events + pos.lastX = pos.nowX; + pos.lastY = pos.nowY; + // mouse position this events + pos.nowX = e.pageX; + pos.nowY = e.pageY; + // distance mouse moved between events + pos.distX = pos.nowX - pos.lastX; + pos.distY = pos.nowY - pos.lastY; + // direction mouse was moving + pos.lastDirX = pos.dirX; + pos.lastDirY = pos.dirY; + // direction mouse is now moving (on both axis) + pos.dirX = pos.distX === 0 ? 0 : pos.distX > 0 ? 1 : -1; + pos.dirY = pos.distY === 0 ? 0 : pos.distY > 0 ? 1 : -1; + // axis mouse is now moving on + var newAx = Math.abs(pos.distX) > Math.abs(pos.distY) ? 1 : 0; + // do nothing on first move + if (firstMoving) { + pos.dirAx = newAx; + pos.moving = true; + return; + } + // calc distance moved on this axis (and direction) + if (pos.dirAx !== newAx) { + pos.distAxX = 0; + pos.distAxY = 0; + } else { + pos.distAxX += Math.abs(pos.distX); + if (pos.dirX !== 0 && pos.dirX !== pos.lastDirX) { + pos.distAxX = 0; + } + pos.distAxY += Math.abs(pos.distY); + if (pos.dirY !== 0 && pos.dirY !== pos.lastDirY) { + pos.distAxY = 0; + } + } + pos.dirAx = newAx; + }, + replaceIndent: function (scope, element, indent, attr) { + attr = attr || 'left'; + angular.element(element.children()[0]).css(attr, scope.$callbacks.calsIndent(indent)); + } + }; + return _$helper; + }] + ); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDPlugin', ['$injector', function ($injector) { + var _fnget = function (name) { + if (angular.isDefined($injector) && $injector.has(name)) { + return $injector.get(name); + } + return null; + }; + return _fnget; + }] + ); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDTemplate', [ + '$templateCache', function ($templateCache) { + var templatePath = 'template/TreeDnD/TreeDnD.html', + copyPath = 'template/TreeDnD/TreeDnDStatusCopy.html', + movePath = 'template/TreeDnD/TreeDnDStatusMove.html', + scopes = {}, + temp, + _$init = { + setMove: function (path, scope) { + if (!scopes[scope.$id]) { + scopes[scope.$id] = {}; + } + scopes[scope.$id].movePath = path; + }, + setCopy: function (path, scope) { + if (!scopes[scope.$id]) { + scopes[scope.$id] = {}; + } + scopes[scope.$id].copyPath = path; + }, + getPath: function () { + return templatePath; + }, + getCopy: function (scope) { + if (scopes[scope.$id] && scopes[scope.$id].copyPath) { + temp = $templateCache.get(scopes[scope.$id].copyPath); + if (temp) { + return temp; + } + } + return $templateCache.get(copyPath); + }, + getMove: function (scope) { + if (scopes[scope.$id] && scopes[scope.$id].movePath) { + temp = $templateCache.get(scopes[scope.$id].movePath); + if (temp) { + return temp; + } + } + return $templateCache.get(movePath); + } + }; + + return _$init; + }] + ); + +angular.module('ntt.TreeDnD') + .factory('$TreeDnDViewport', fnInitTreeDnDViewport); + +fnInitTreeDnDViewport.$inject = ['$window', '$document', '$timeout', '$q', '$compile']; + +function fnInitTreeDnDViewport($window, $document, $timeout, $q, $compile) { + + var viewport = null, + isUpdating = false, + isRender = false, + updateAgain = false, + viewportRect, + items = [], + nodeTemplate, + updateTimeout, + renderTime, + $initViewport = { + setViewport: setViewport, + getViewport: getViewport, + add: add, + setTemplate: setTemplate, + getItems: getItems, + updateDelayed: updateDelayed + }, + eWindow = angular.element($window); + + eWindow.on('load resize scroll', updateDelayed); + + return $initViewport; + + function update() { + + viewportRect = { + width: eWindow.prop('offsetWidth') || document.documentElement.clientWidth, + height: eWindow.prop('offsetHeight') || document.documentElement.clientHeight, + top: $document[0].body.scrollTop || $document[0].documentElement.scrollTop, + left: $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft + }; + + if (isUpdating || isRender) { + updateAgain = true; + return; + } + isUpdating = true; + + recursivePromise(); + } + + function recursivePromise() { + if (isRender) { + return; + } + + var number = number > 0 ? number : items.length, item; + + if (number > 0) { + item = items[0]; + + isRender = true; + renderTime = $timeout(function () { + //item.element.html(nodeTemplate); + //$compile(item.element.contents())(item.scope); + + items.splice(0, 1); + isRender = false; + number--; + $timeout.cancel(renderTime); + recursivePromise(); + }, 0); + + } else { + isUpdating = false; + if (updateAgain) { + updateAgain = false; + update(); + } + } + + } + + /** + * Check if a point is inside specified bounds + * @param x + * @param y + * @param bounds + * @returns {boolean} + */ + function pointIsInsideBounds(x, y, bounds) { + return x >= bounds.left && + y >= bounds.top && + x <= bounds.left + bounds.width && + y <= bounds.top + bounds.height; + } + + /** + * @name setViewport + * @desciption Set the viewport element + * @param element + */ + function setViewport(element) { + viewport = element; + } + + /** + * Return the current viewport + * @returns {*} + */ + function getViewport() { + return viewport; + } + + /** + * trigger an update + */ + function updateDelayed() { + $timeout.cancel(updateTimeout); + updateTimeout = $timeout(function () { + update(); + }, 0); + } + + /** + * Add listener for event + * @param element + * @param callback + */ + function add(scope, element) { + updateDelayed(); + items.push({ + element: element, + scope: scope + }); + } + + function setTemplate(scope, template) { + nodeTemplate = template; + } + + /** + * Get list of items + * @returns {Array} + */ + function getItems() { + return items; + } +} + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDDrag', [ + '$timeout', '$TreeDnDHelper', + function ($timeout, $TreeDnDHelper) { + function _fnPlaceHolder(e, $params) { + if ($params.placeElm) { + var _offset = $TreeDnDHelper.offset($params.placeElm); + if (_offset.top <= e.pageY && e.pageY <= _offset.top + _offset.height && + _offset.left <= e.pageX && e.pageX <= _offset.left + _offset.width + ) { + return true; + } + } + return false; + } + + function _fnDragStart(e, $params) { + if (!$params.hasTouch && (e.button === 2 || e.which === 3)) { + // disable right click + return; + } + if (e.uiTreeDragging || e.originalEvent && e.originalEvent.uiTreeDragging) { // event has already fired in other scope. + return; + } + // the element which is clicked. + var eventElm = angular.element(e.target), + eventScope = eventElm.scope(); + if (!eventScope || !eventScope.$type) { + return; + } + // if (eventScope.$type !== 'TreeDnDNode') { // Check if it is a node or a handle + // return; + // } + + if (eventScope.$type !== 'TreeDnDNodeHandle') { // If the node has a handle, then it should be clicked by the handle + return; + } + + var eventElmTagName = eventElm.prop('tagName').toLowerCase(), + dragScope, + _$scope = $params.$scope; + if (eventElmTagName === 'input' + || eventElmTagName === 'textarea' + || eventElmTagName === 'button' + || eventElmTagName === 'select') { // if it's a input or button, ignore it + return; + } + // check if it or it's parents has a 'data-nodrag' attribute + while (eventElm && eventElm[0] && eventElm[0] !== $params.element) { + if ($TreeDnDHelper.nodrag(eventElm)) { // if the node mark as `nodrag`, DONOT drag it. + return; + } + eventElm = eventElm.parent(); + } + + e.uiTreeDragging = true; // stop event bubbling + if (e.originalEvent) { + e.originalEvent.uiTreeDragging = true; + } + e.preventDefault(); + + dragScope = eventScope.getScopeNode(); + + $params.dragInfo = $TreeDnDHelper.dragInfo(dragScope); + + if (!_$scope.$callbacks.beforeDrag(dragScope, $params.dragInfo)) { + return; + } + + $params.firstMoving = true; + _$scope.setDragging($params.dragInfo); + + var eventObj = $TreeDnDHelper.eventObj(e); + $params.pos = $TreeDnDHelper.positionStarted(eventObj, dragScope.$element); + + if (dragScope.isTable) { + $params.dragElm = angular.element($params.$window.document.createElement('table')) + .addClass(_$scope.$class.tree) + .addClass(_$scope.$class.drag) + .addClass(_$scope.$tree_class); + } else { + $params.dragElm = angular.element($params.$window.document.createElement('ul')) + .addClass(_$scope.$class.drag) + .addClass('tree-dnd-nodes') + .addClass(_$scope.$tree_class); + } + + $params.dragElm.css( + { + 'width': $TreeDnDHelper.width(dragScope.$element) + 'px', + 'z-index': 9995 + } + ); + + $params.offsetEdge = 0; + var _width = $TreeDnDHelper.width(dragScope.$element), + _scope = dragScope, + _element = _scope.$element, + _clone, + _needCollapse = !!_$scope.enabledCollapse, + _copied = false, + _tbody, + _frag; + + if (_scope.isTable) { + $params.offsetEdge = $params.dragInfo.node.__level__ - 1; + _tbody = angular.element(document.createElement('tbody')); + _frag = angular.element(document.createDocumentFragment()); + + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element) { + if (!_copied) { + _clone = _element.clone(); + + $TreeDnDHelper.replaceIndent( + _$scope, + _clone, + _node.__level__ - $params.offsetEdge, + 'padding-left' + ); + + _frag.append(_clone); + + // skip all, just clone parent + if (_needCollapse) { + _copied = true; + } + + // hide if have status Move; + if (_$scope.enabledMove && _$scope.$class.hidden && + (!_parent || _node.__visible__ || _parent.__visible__ && _parent.__expanded__)) { + _element.addClass(_$scope.$class.hidden); + } + } + } + // skip children of node not expand. + return _copied || _node.__visible__ === false || _node.__expanded__ === false; + + }, null, !_needCollapse + ); + _tbody.append(_frag); + $params.dragElm.append(_tbody); + } else { + + _clone = _element.clone(); + if (_needCollapse) { + _clone[0].querySelector('[tree-dnd-nodes]').remove(); + } + + // hide if have status Move; + $params.dragElm.append(_clone); + if (_$scope.enabledMove && _$scope.$class.hidden) { + _element.addClass(_$scope.$class.hidden); + } + } + + $params.dragElm.css( + { + 'left': eventObj.pageX - $params.pos.offsetX + _$scope.$callbacks.calsIndent( + $params.offsetEdge + 1, + true, + true + ) + 'px', + 'top': eventObj.pageY - $params.pos.offsetY + 'px' + } + ); + // moving item with descendant + $params.$document.find('body').append($params.dragElm); + if (_$scope.$callbacks.droppable()) { + $params.placeElm = _$scope.initPlace(dragScope.$element, $params.dragElm); + + if (dragScope.isTable) { + $TreeDnDHelper.replaceIndent(_$scope, $params.placeElm, $params.dragInfo.node.__level__); + } + + $params.placeElm.css('width', _width); + } + + _$scope.showPlace(); + _$scope.targeting = true; + + if (_$scope.enabledStatus) { + _$scope.refreshStatus(); + _$scope.setPositionStatus(e); + } + + angular.element($params.$document).bind('touchend', $params.dragEndEvent); + angular.element($params.$document).bind('touchcancel', $params.dragEndEvent); + angular.element($params.$document).bind('touchmove', $params.dragMoveEvent); + angular.element($params.$document).bind('mouseup', $params.dragEndEvent); + angular.element($params.$document).bind('mousemove', $params.dragMoveEvent); + angular.element($params.$document).bind('mouseleave', $params.dragCancelEvent); + + $params.document_height = Math.max( + $params.body.scrollHeight, + $params.body.offsetHeight, + $params.html.clientHeight, + $params.html.scrollHeight, + $params.html.offsetHeight + ); + + $params.document_width = Math.max( + $params.body.scrollWidth, + $params.body.offsetWidth, + $params.html.clientWidth, + $params.html.scrollWidth, + $params.html.offsetWidth + ); + } + + function _fnDragMove(e, $params) { + var _$scope = $params.$scope; + if (!$params.dragStarted) { + if (!$params.dragDelaying) { + $params.dragStarted = true; + _$scope.$safeApply( + function () { + _$scope.$callbacks.dragStart($params.dragInfo); + } + ); + } + return; + } + + if ($params.dragElm) { + e.preventDefault(); + if ($params.$window.getSelection) { + $params.$window.getSelection().removeAllRanges(); + } else if ($params.$window.document.selection) { + $params.$window.document.selection.empty(); + } + + var eventObj = $TreeDnDHelper.eventObj(e), + leftElmPos = eventObj.pageX - $params.pos.offsetX, + topElmPos = eventObj.pageY - $params.pos.offsetY; + + //dragElm can't leave the screen on the left + if (leftElmPos < 0) { + leftElmPos = 0; + } + + //dragElm can't leave the screen on the top + if (topElmPos < 0) { + topElmPos = 0; + } + + //dragElm can't leave the screen on the bottom + if (topElmPos + 10 > $params.document_height) { + topElmPos = $params.document_height - 10; + } + + //dragElm can't leave the screen on the right + if (leftElmPos + 10 > $params.document_width) { + leftElmPos = $params.document_width - 10; + } + + $params.dragElm.css( + { + 'left': leftElmPos + _$scope.$callbacks.calsIndent( + $params.offsetEdge + 1, + true, + true + ) + 'px', + 'top': topElmPos + 'px' + } + ); + + if (_$scope.enabledStatus) { + _$scope.setPositionStatus(e); + } + + var top_scroll = window.pageYOffset || $params.$window.document.documentElement.scrollTop, + bottom_scroll = top_scroll + (window.innerHeight || $params.$window.document.clientHeight || $params.$window.document.clientHeight); + // to scroll down if cursor y-position is greater than the bottom position the vertical scroll + if (bottom_scroll < eventObj.pageY && bottom_scroll <= $params.document_height) { + window.scrollBy(0, 10); + } + // to scroll top if cursor y-position is less than the top position the vertical scroll + if (top_scroll > eventObj.pageY) { + window.scrollBy(0, -10); + } + + $TreeDnDHelper.positionMoved(e, $params.pos, $params.firstMoving); + + if ($params.firstMoving) { + $params.firstMoving = false; + return; + } + // check if add it as a child node first + + var targetX = eventObj.pageX - $params.$window.document.body.scrollLeft, + targetY = eventObj.pageY - (window.pageYOffset || $params.$window.document.documentElement.scrollTop), + + targetElm, + targetScope, + targetBefore, + targetOffset, + isChanged = true, + isVeritcal = true, + isEmpty, + isSwapped, + _scope, + _target, + _parent, + _info = $params.dragInfo, + _move = _info.move, + _drag = _info.node, + _drop = _info.drop, + treeScope = _info.target, + fnSwapTree, + isHolder = _fnPlaceHolder(e, $params); + + if (!isHolder) { + /* when using elementFromPoint() inside an iframe, you have to call + elementFromPoint() twice to make sure IE8 returns the correct value + $params.$window.document.elementFromPoint(targetX, targetY);*/ + + targetElm = angular.element( + $params.$window.document.elementFromPoint( + targetX, + targetY + ) + ); + + targetScope = targetElm.scope(); + if (!targetScope || !targetScope.$callbacks || !targetScope.$callbacks.droppable()) { + // Not allowed Drop Item + return; + } + + fnSwapTree = function () { + treeScope = targetScope.getScopeTree(); + _target = _info.target; + + if (_info.target !== treeScope) { + // Replace by place-holder new + _target.hidePlace(); + _target.targeting = false; + treeScope.targeting = true; + + _info.target = treeScope; + $params.placeElm = treeScope.initPlace(targetScope.$element, $params.dragElm); + + _target = null; + isSwapped = true; + } + return true; + }; + + if (angular.isFunction(targetScope.getScopeNode)) { + targetScope = targetScope.getScopeNode(); + if (!fnSwapTree()) { + return; + } + } else { + if (targetScope.$type === 'TreeDnDNodes' || targetScope.$type === 'TreeDnD') { + if (targetScope.tree_nodes) { + if (targetScope.tree_nodes.length === 0) { + if (!fnSwapTree()) { + return; + } + // Empty + isEmpty = true; + } + } else { + return; + } + } else { + return; + } + } + } + + if ($params.pos.dirAx && !isSwapped || isHolder) { + isVeritcal = false; + targetScope = _info.scope; + } + + if (!targetScope.$element && !targetScope) { + return; + } + + if (isEmpty) { + _move.parent = null; + _move.pos = 0; + + _drop = null; + } else { + // move vertical + if (isVeritcal) { + targetElm = targetScope.$element; // Get the element of tree-dnd-node + if (angular.isUndefinedOrNull(targetElm)) { + return; + } + targetOffset = $TreeDnDHelper.offset(targetElm); + + if (targetScope.horizontal && !targetScope.isTable) { + targetBefore = eventObj.pageX < targetOffset.left + $TreeDnDHelper.width(targetElm) / 2; + } else { + if (targetScope.isTable) { + targetBefore = eventObj.pageY < targetOffset.top + $TreeDnDHelper.height(targetElm) / 2; + } else { + var _height = $TreeDnDHelper.height(targetElm); + + if (targetScope.getElementChilds()) { + _height -= -$TreeDnDHelper.height(targetScope.getElementChilds()); + } + + if (eventObj.pageY > targetOffset.top + _height) { + return; + } + + targetBefore = eventObj.pageY < targetOffset.top + _height / 2; + } + } + + if (!angular.isFunction(targetScope.getData)) { + return; + } + + _target = targetScope.getData(); + _parent = targetScope.getNode(_target.__parent_real__); + + if (targetBefore) { + var _prev = targetScope.getPrevSibling(_target); + + _move.parent = _parent; + _move.pos = angular.isDefined(_prev) ? _prev.__index__ + 1 : 0; + + _drop = _prev; + } else { + if (_target.__expanded__ && !(_target.__children__.length === 1 && _target.__index_real__ === _drag.__parent_real__)) { + _move.parent = _target; + _move.pos = 0; + + _drop = null; + } else { + _move.parent = _parent; + _move.pos = _target.__index__ + 1; + + _drop = _target; + } + } + } else { + // move horizontal + if ($params.pos.dirAx && $params.pos.distAxX >= treeScope.dragBorder) { + $params.pos.distAxX = 0; + // increase horizontal level if previous sibling exists and is not collapsed + if ($params.pos.distX > 0) { + _parent = _drop; + if (!_parent) { + if (_move.pos - 1 >= 0) { + _parent = _move.parent.__children__[_move.pos - 1]; + } else { + return; + } + } + + if (_info.drag === _info.target && _parent === _drag && _$scope.enabledMove) { + _parent = treeScope.getPrevSibling(_parent); + } + + if (_parent && _parent.__visible__) { + var _len = _parent.__children__.length; + + _move.parent = _parent; + _move.pos = _len; + + if (_len > 0) { + _drop = _parent.__children__[_len - 1]; + } else { + _drop = null; + } + } else { + // Not changed + return; + } + } else if ($params.pos.distX < 0) { + _target = _move.parent; + if (_target && + (_target.__children__.length === 0 || + _target.__children__.length - 1 < _move.pos || + _info.drag === _info.target && + _target.__index_real__ === _drag.__parent_real__ && + _target.__children__.length - 1 === _drag.__index__ && _$scope.enabledMove) + ) { + _parent = treeScope.getNode(_target.__parent_real__); + + _move.parent = _parent; + _move.pos = _target.__index__ + 1; + + _drop = _target; + } else { + // Not changed + return; + } + } else { + return; + } + } else { + // limited + return; + } + } + } + + if (_info.drag === _info.target && + _move.parent && + _drag.__parent_real__ === _move.parent.__index_real__ && + _drag.__index__ === _move.pos + ) { + isChanged = false; + } + + if (treeScope.$callbacks.accept(_info, _move, isChanged)) { + _info.move = _move; + _info.drop = _drop; + _info.changed = isChanged; + _info.scope = targetScope; + + if (targetScope.isTable) { + $TreeDnDHelper.replaceIndent( + treeScope, + $params.placeElm, + angular.isUndefinedOrNull(_move.parent) ? 1 : _move.parent.__level__ + 1 + ); + + if (_drop) { + _parent = (_move.parent ? _move.parent.__children__ : null ) || _info.target.treeData; + + if (_drop.__index__ < _parent.length - 1) { + // Find fast + _drop = _parent[_drop.__index__ + 1]; + _scope = _info.target.getScope(_drop); + _scope.$element[0].parentNode.insertBefore( + $params.placeElm[0], + _scope.$element[0] + ); + } else { + _target = _info.target.getLastDescendant(_drop); + _scope = _info.target.getScope(_target); + _scope.$element.after($params.placeElm); + } + } else { + _scope = _info.target.getScope(_move.parent); + if (_scope) { + if (_move.parent) { + _scope.$element.after($params.placeElm); + + } else { + _scope.getElementChilds().prepend($params.placeElm); + } + } + } + } else { + _scope = _info.target.getScope(_drop || _move.parent); + if (_drop) { + _scope.$element.after($params.placeElm); + } else { + _scope.getElementChilds().prepend($params.placeElm); + } + } + + treeScope.showPlace(); + + _$scope.$safeApply( + function () { + _$scope.$callbacks.dragMove(_info); + } + ); + } + + } + } + + function _fnDragEnd(e, $params) { + e.preventDefault(); + if ($params.dragElm) { + var _passed = false, + _$scope = $params.$scope, + _scope = _$scope.getScope($params.dragInfo.node), + _element = _scope.$element; + + _$scope.$safeApply( + function () { + _passed = _$scope.$callbacks.beforeDrop($params.dragInfo); + } + ); + + // rollback all + if (_scope.isTable) { + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + return _node.__visible__ === false || _node.__expanded__ === false + }, null, true + ); + } else { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + + $params.dragElm.remove(); + $params.dragElm = null; + + if (_$scope.enabledStatus) { + _$scope.hideStatus(); + } + + if (_$scope.$$apply) { + _$scope.$safeApply( + function () { + var _status = _$scope.$callbacks.dropped( + $params.dragInfo, + _passed + ); + + _$scope.$callbacks.dragStop($params.dragInfo, _status); + clearData(); + } + ); + } else { + _fnBindDrag($params); + _$scope.$safeApply( + function () { + _$scope.$callbacks.dragStop($params.dragInfo, false); + clearData(); + } + ); + } + + } + + function clearData() { + $params.dragInfo.target.hidePlace(); + $params.dragInfo.target.targeting = false; + + $params.dragInfo = null; + _$scope.$$apply = false; + _$scope.setDragging(null); + } + + angular.element($params.$document).unbind('touchend', $params.dragEndEvent); // Mobile + angular.element($params.$document).unbind('touchcancel', $params.dragEndEvent); // Mobile + angular.element($params.$document).unbind('touchmove', $params.dragMoveEvent); // Mobile + angular.element($params.$document).unbind('mouseup', $params.dragEndEvent); + angular.element($params.$document).unbind('mousemove', $params.dragMoveEvent); + angular.element($params.$window.document.body).unbind('mouseleave', $params.dragCancelEvent); + } + + function _fnDragStartEvent(e, $params) { + if ($params.$scope.$callbacks.draggable()) { + _fnDragStart(e, $params); + } + } + + function _fnBindDrag($params) { + $params.element.bind( + 'touchstart mousedown', function (e) { + $params.dragDelaying = true; + $params.dragStarted = false; + _fnDragStartEvent(e, $params); + $params.dragTimer = $timeout( + function () { + $params.dragDelaying = false; + }, $params.$scope.dragDelay + ); + } + ); + + $params.element.bind( + 'touchend touchcancel mouseup', function () { + $timeout.cancel($params.dragTimer); + } + ); + } + + function _fnKeydownHandler(e, $params) { + var _$scope = $params.$scope; + if (e.keyCode === 27) { + if (_$scope.enabledStatus) { + _$scope.hideStatus(); + } + + _$scope.$$apply = false; + _fnDragEnd(e, $params); + } else { + if (_$scope.enabledHotkey && e.shiftKey) { + _$scope.enableMove(true); + if (_$scope.enabledStatus) { + _$scope.refreshStatus(); + } + + if (!$params.dragInfo) { + return; + } + + var _scope = _$scope.getScope($params.dragInfo.node), + _element = _scope.$element; + + if (_scope.isTable) { + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) { + if (_$scope.$class.hidden) { + _element.addClass(_$scope.$class.hidden); + } + } + return _node.__visible__ === false || _node.__expanded__ === false + + }, null, true + ); + } else { + if (_$scope.$class.hidden) { + _element.addClass(_$scope.$class.hidden); + } + } + } + } + } + + function _fnKeyupHandler(e, $params) { + var _$scope = $params.$scope; + if (_$scope.enabledHotkey && !e.shiftKey) { + _$scope.enableMove(false); + + if (_$scope.enabledStatus) { + _$scope.refreshStatus(); + } + + if (!$params.dragInfo) { + return; + } + + var _scope = _$scope.getScope($params.dragInfo.node), + _element = _scope.$element; + + if (_scope.isTable) { + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + return _node.__visible__ === false || _node.__expanded__ === false + }, null, true + ); + } else { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + } + } + + function _$init(scope, element, $window, $document) { + var $params = { + hasTouch: 'ontouchstart' in window, + firstMoving: null, + dragInfo: null, + pos: null, + placeElm: null, + dragElm: null, + dragDelaying: true, + dragStarted: false, + dragTimer: null, + body: document.body, + html: document.documentElement, + document_height: null, + document_width: null, + offsetEdge: null, + $scope: scope, + $window: $window, + $document: $document, + element: element, + bindDrag: function () { + _fnBindDrag($params); + }, + dragEnd: function (e) { + _fnDragEnd(e, $params); + }, + dragMoveEvent: function (e) { + _fnDragMove(e, $params); + }, + dragEndEvent: function (e) { + scope.$$apply = true; + _fnDragEnd(e, $params); + }, + dragCancelEvent: function (e) { + _fnDragEnd(e, $params); + } + }, + keydownHandler = function (e) { + return _fnKeydownHandler(e, $params); + }, + keyupHandler = function (e) { + return _fnKeyupHandler(e, $params); + }; + + scope.dragEnd = function (e) { + $params.dragEnd(e); + }; + + $params.bindDrag(); + + angular.element($window.document.body).bind('keydown', keydownHandler); + angular.element($window.document.body).bind('keyup', keyupHandler); + //unbind handler that retains scope + scope.$on( + '$destroy', function () { + angular.element($window.document.body).unbind('keydown', keydownHandler); + angular.element($window.document.body).unbind('keyup', keyupHandler); + if (scope.statusElm) { + scope.statusElm.remove(); + } + + if (scope.placeElm) { + scope.placeElm.remove(); + } + } + ); + } + + return _$init; + } + ] +); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDControl', function () { + var _target, _parent, + i, len; + + function fnSetCollapse(node) { + node.__expanded__ = false; + } + + function fnSetExpand(node) { + node.__expanded__ = true; + } + + function _$init(scope) { + var n, tree = { + selected_node: null, + for_all_descendants: scope.for_all_descendants, + select_node: function (node) { + if (!node) { + if (tree.selected_node) { + delete tree.selected_node.__selected__; + } + tree.selected_node = null; + return null; + } + + if (node !== tree.selected_node) { + if (tree.selected_node) { + delete tree.selected_node.__selected__; + } + node.__selected__ = true; + tree.selected_node = node; + tree.expand_all_parents(node); + if (angular.isFunction(tree.on_select)) { + tree.on_select(node); + } + } + return node; + }, + deselect_node: function () { + _target = null; + if (tree.selected_node) { + delete tree.selected_node.__selected__; + _target = tree.selected_node; + tree.selected_node = null; + } + return _target; + }, + get_parent: function (node) { + if (node && node.__parent_real__ !== null) { + return scope.tree_nodes[node.__parent_real__]; + } + return null; + }, + for_all_ancestors: function (child, fn) { + _parent = tree.get_parent(child); + if (_parent) { + if (fn(_parent)) { + return false; + } + + return tree.for_all_ancestors(_parent, fn); + } + return true; + }, + expand_all_parents: function (child) { + child = child || tree.selected_node; + if (typeof child === 'object') { + tree.for_all_ancestors( + child, fnSetExpand + ) + } + }, + collapse_all_parents: function (child) { + child = child || tree.selected_node; + if (typeof child === 'object') { + tree.for_all_ancestors( + child, fnSetCollapse + ) + } + }, + + reload_data: function () { + return scope.reload_data(); + }, + add_node: function (parent, new_node, index) { + if (typeof index !== 'number') { + if (parent) { + parent.__children__.push(new_node); + parent.__expanded__ = true; + } else { + scope.treeData.push(new_node); + } + } else { + if (parent) { + parent.__children__.splice(index, 0, new_node); + parent.__expanded__ = true; + } else { + scope.treeData.splice(index, 0, new_node); + } + } + return new_node; + }, + add_node_root: function (new_node) { + tree.add_node(null, new_node); + return new_node; + }, + expand_all: function () { + len = scope.treeData.length; + for (i = 0; i < len; i++) { + tree.for_all_descendants( + scope.treeData[i], fnSetExpand + ); + } + }, + collapse_all: function () { + len = scope.treeData.length; + for (i = 0; i < len; i++) { + tree.for_all_descendants( + scope.treeData[i], fnSetCollapse + ); + } + }, + remove_node: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + if (node.__parent_real__ !== null) { + _parent = tree.get_parent(node).__children__; + } else { + _parent = scope.treeData; + } + + _parent.splice(node.__index__, 1); + + tree.reload_data(); + + if (tree.selected_node === node) { + tree.selected_node = null; + } + } + }, + expand_node: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object' && node.__expanded__) { + node.__expanded__ = true; + return node; + } + }, + collapse_node: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + node.__expanded__ = false; + return node; + } + }, + get_selected_node: function () { + return tree.selected_node; + }, + get_first_node: function () { + len = scope.treeData.length; + if (len > 0) { + return scope.treeData[0]; + } + return null; + }, + get_children: function (node) { + return node.__children__; + }, + get_siblings: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + _parent = tree.get_parent(node); + if (_parent) { + _target = _parent.__children__; + } else { + _target = scope.treeData; + } + return _target; + } + }, + get_next_sibling: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + _target = tree.get_siblings(node); + n = _target.length; + if (node.__index__ < n) { + return _target[node.__index__ + 1]; + } + } + }, + get_prev_sibling: function (node) { + node = node || tree.selected_node; + _target = tree.get_siblings(node); + if (node.__index__ > 0) { + return _target[node.__index__ - 1]; + } + }, + get_first_child: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + _target = node.__children__; + if (_target && _target.length > 0) { + return node.__children__[0]; + } + } + return null; + }, + get_closest_ancestor_next_sibling: function (node) { + node = node || tree.selected_node; + _target = tree.get_next_sibling(node); + if (_target) { + return _target; + } + + _parent = tree.get_parent(node); + return tree.get_closest_ancestor_next_sibling(_parent); + }, + get_next_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_first_child(node); + if (_target) { + return _target; + } else { + return tree.get_closest_ancestor_next_sibling(node); + } + } + }, + get_prev_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_prev_sibling(node); + if (_target) { + return tree.get_last_descendant(_target); + } + + _parent = tree.get_parent(node); + return _parent; + } + }, + get_last_descendant: scope.getLastDescendant, + select_parent_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _parent = tree.get_parent(node); + if (_parent) { + return tree.select_node(_parent); + } + } + }, + select_first_node: function () { + var firstNode = tree.get_first_node(); + return tree.select_node(firstNode); + }, + select_next_sibling: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_next_sibling(node); + if (_target) { + return tree.select_node(_target); + } + } + }, + select_prev_sibling: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_prev_sibling(node); + if (_target) { + return tree.select_node(_target); + } + } + }, + select_next_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_next_node(node); + if (_target) { + return tree.select_node(_target); + } + } + }, + select_prev_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_prev_node(node); + if (_target) { + return tree.select_node(_target); + } + } + } + }; + angular.extend(scope.tree, tree); + return scope.tree; + } + + return _$init; + } +); + +angular.module('template/TreeDnD/TreeDnD.html', []).run( + [ + '$templateCache', function ($templateCache) { + $templateCache.put( + 'template/TreeDnD/TreeDnD.html', + ['', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '
', + ' {{expandingProperty.displayName || expandingProperty.field || expandingProperty}}', + ' <\/th>', + ' ', + ' {{col.displayName || col.field}}', + '
', + ' ', + ' ', + ' ', + ' {{node[expandingProperty.field] || node[expandingProperty]}}', + ' ', + ' {{node[col.field]}}', + '
'].join('\n') + ); + + $templateCache.put( + 'template/TreeDnD/TreeDnDStatusCopy.html', + '' + ); + + $templateCache.put( + 'template/TreeDnD/TreeDnDStatusMove.html', + '' + ); + }] +); + + function isUndefinedOrNull(val) { + return angular.isUndefined(val) || val === null; + } + + function isDefined(val) { + return !(angular.isUndefined(val) || val === null); + } +})(); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.js b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.js new file mode 100644 index 0000000..ce6b824 --- /dev/null +++ b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.js @@ -0,0 +1,3381 @@ +/** + * The MIT License (MIT) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * @preserve + */ + +/** + * Implementing TreeDnD & Event DrapnDrop (allow drag multi tree-table include all type: table, ol, ul) + * Demo: http://thienhung1989.github.io/angular-tree-dnd + * Github: https://github.com/thienhung1989/angular-tree-dnd + * @version 3.0.5 + * @preserve + * (c) 2015 Nguyuễn Thiện Hùng - + */ +(function () { + 'use strict'; + angular.isUndefinedOrNull = isUndefinedOrNull; + + angular.isDefined = isDefined; + + angular.module('ntt.TreeDnD', ['template/TreeDnD/TreeDnD.html']) + .constant( + '$TreeDnDClass', { + tree: 'tree-dnd', + empty: 'tree-dnd-empty', + hidden: 'tree-dnd-hidden', + node: 'tree-dnd-node', + nodes: 'tree-dnd-nodes', + handle: 'tree-dnd-handle', + place: 'tree-dnd-placeholder', + drag: 'tree-dnd-drag', + status: 'tree-dnd-status', + icon: { + '1': 'glyphicon glyphicon-minus', + '0': 'glyphicon glyphicon-plus', + '-1': 'glyphicon glyphicon-file' + } + } + );angular.module('ntt.TreeDnD') + .directive( + 'compile', [ + '$compile', function ($compile) { + return { + restrict: 'A', + link: function (scope, element, attrs) { + scope.$watch( + attrs.compile, function (new_val) { + if (new_val) { + if (angular.isFunction(element.empty)) { + element.empty(); + } else { + element.html(''); + } + + element.append($compile(new_val)(scope)); + } + } + ); + } + }; + }] +) + .directive( + 'compileReplace', [ + '$compile', function ($compile) { + return { + restrict: 'A', + link: function (scope, element, attrs) { + scope.$watch( + attrs.compileReplace, function (new_val) { + if (new_val) { + element.replaceWith($compile(new_val)(scope)); + } + } + ); + } + }; + }] +); + +angular.module('ntt.TreeDnD') .directive( 'treeDndNodeHandle', function () { return { restrict: 'A', scope: true, link: function (scope, element, attrs) { scope.$type = 'TreeDnDNodeHandle'; if (scope.$class.handle) { element.addClass(scope.$class.handle); } } }; } ); + +angular.module('ntt.TreeDnD') + .directive( + 'treeDndNode', ['$TreeDnDViewport', '$timeout', function ($TreeDnDViewport, $timeout) { + return { + restrict: 'A', + replace: true, + link: fnLink + }; + function fnLink(scope, element, attrs) { + + scope.$node_class = ''; + + if (scope.$class.node) { + element.addClass(scope.$class.node); + scope.$node_class = scope.$class.node; + } + var enabledDnD = typeof scope.dragEnabled === 'boolean' || typeof scope.dropEnabled === 'boolean', + keyNode = attrs.treeDndNode, + first = true, + childsElem; + $TreeDnDViewport.add(scope, element); + + if (enabledDnD) { + scope.$type = 'TreeDnDNode'; + + scope.getData = function () { + return scope[keyNode]; + }; + } + + scope.$element = element; + scope[keyNode].__inited__ = true; + + scope.getElementChilds = function () { + return angular.element(element[0].querySelector('[tree-dnd-nodes]')); + }; + + scope.setScope(scope, scope[keyNode]); + + scope.getScopeNode = function () { + return scope; + }; + + var objprops = [], + objexpr, + i, keyO = Object.keys(scope[keyNode]), + lenO = keyO.length, + hashKey = scope[keyNode].__hashKey__, + skipAttr = [ + '__visible__', + '__children__', + '__level__', + '__index__', + '__index_real__', + + '__parent__', + '__parent_real__', + '__dept__', + '__icon__', + '__icon_class__' + ], + keepAttr = [ + '__expanded__' + ], + lenKeep = keepAttr.length; + + // skip __visible__ + for (i = 0; i < lenO + lenKeep; i++) { + if (i < lenO) { + if (skipAttr.indexOf(keyO[i]) === -1) { + objprops.push(keyNode + '.' + keyO[i]); + } + } else { + if (keyO.indexOf(keepAttr[i - lenO]) === -1) { + objprops.push(keyNode + '.' + keepAttr[i - lenO]); + } + } + } + + objexpr = '[' + objprops.join(',') + ']'; + + scope.$watch(objexpr, fnWatchNode, true); + + scope.$on('$destroy', function () { + scope.deleteScope(scope, scope[keyNode]); + }); + + function fnWatchNode(newVal, oldVal, scope) { + + var nodeOf = scope[keyNode], + _icon; + + if (first) { + _icon = nodeOf.__icon__; + nodeOf.__icon_class__ = scope.$class.icon[_icon]; + } else { + + var parentReal = nodeOf.__parent_real__, + parentNode = scope.tree_nodes[parentReal] || null, + _childs = nodeOf.__children__, + _len = _childs.length, + _i; + + if (!nodeOf.__inited__) { + nodeOf.__inited__ = true; + } + + if (nodeOf.__hashKey__ !== hashKey) { + // clear scope in $globals + scope.deleteScope(scope, nodeOf); + + // add new scope into $globals + scope.setScope(scope, nodeOf); + hashKey = nodeOf.__hashKey__; + } + + if (parentNode && (!parentNode.__expanded__ || !parentNode.__visible__)) { + element.addClass(scope.$class.hidden); + nodeOf.__visible__ = false; + } else { + element.removeClass(scope.$class.hidden); + nodeOf.__visible__ = true; + } + + if (_len === 0) { + _icon = -1; + } else { + if (nodeOf.__expanded__) { + _icon = 1; + } else { + _icon = 0; + } + } + + nodeOf.__icon__ = _icon; + nodeOf.__icon_class__ = scope.$class.icon[_icon]; + + if (scope.isTable) { + for (_i = 0; _i < _len; _i++) { + scope.for_all_descendants(_childs[_i], scope.hiddenChild, nodeOf, true); + } + } else { + if (!childsElem) { + childsElem = scope.getElementChilds(); + } + + if (nodeOf.__expanded__) { + childsElem.removeClass(scope.$class.hidden); + } else { + childsElem.addClass(scope.$class.hidden); + } + } + + } + + first = false; + + } + } + }] +); + +angular.module('ntt.TreeDnD') + .directive( + 'treeDndNodes', function () { + return { + restrict: 'A', + replace: true, + link: function (scope, element/*, attrs*/) { + scope.$type = 'TreeDnDNodes'; + + if (scope.$class.nodes) { + element.addClass(scope.$class.nodes); + scope.$nodes_class = scope.$class.nodes; + } else { + scope.$nodes_class = ''; + } + } + }; + } +); + +angular.module('ntt.TreeDnD') + .directive( + 'treeDnd', fnInitTreeDnD); + +fnInitTreeDnD.$inject = [ + '$timeout', '$http', '$compile', '$parse', '$window', '$document', '$templateCache', + '$TreeDnDTemplate', '$TreeDnDClass', '$TreeDnDHelper', '$TreeDnDPlugin', '$TreeDnDViewport' +]; + +function fnInitTreeDnD($timeout, $http, $compile, $parse, $window, $document, $templateCache, + $TreeDnDTemplate, $TreeDnDClass, $TreeDnDHelper, $TreeDnDPlugin, $TreeDnDViewport +) { + return { + restrict: 'E', + scope: true, + replace: true, + controller: ['$scope', '$element', '$attrs', fnController], + compile: fnCompile + }; + + function fnController($scope, $element, $attrs) { + $scope.indent = 20; + $scope.indent_plus = 15; + $scope.indent_unit = 'px'; + $scope.$tree_class = 'table'; + $scope.primary_key = '__uid__'; + + $scope.$type = 'TreeDnD'; + // $scope.enabledFilter = null; + $scope.colDefinitions = []; + $scope.$globals = {}; + $scope.$class = {}; + + $scope.treeData = []; + $scope.tree_nodes = []; + + $scope.$class = angular.copy($TreeDnDClass); + angular.extend( + $scope.$class.icon, { + '1': $attrs.iconExpand || 'glyphicon glyphicon-minus', + '0': $attrs.iconCollapse || 'glyphicon glyphicon-plus', + '-1': $attrs.iconLeaf || 'glyphicon glyphicon-file' + } + ); + + $scope.for_all_descendants = function (node, fn, parent, checkSibling) { + if (angular.isFunction(fn)) { + var _i, _len, _nodes; + + if (fn(node, parent)) { + // have error or need ignore children + return false; + } + _nodes = node.__children__; + _len = _nodes ? _nodes.length : 0; + for (_i = 0; _i < _len; _i++) { + if (!$scope.for_all_descendants(_nodes[_i], fn, node) && !checkSibling) { + // skip sibling of node checking + return false; + } + } + } + // succeed then continue + return true; + }; + + $scope.getLastDescendant = function (node) { + var last_child, n; + if (!node) { + node = $scope.tree ? $scope.tree.selected_node : false; + } + if (node === false) { + return false; + } + n = node.__children__.length; + if (n === 0) { + return node; + } else { + last_child = node.__children__[n - 1]; + return $scope.getLastDescendant(last_child); + } + }; + + $scope.getElementChilds = function () { + return angular.element($element[0].querySelector('[tree-dnd-nodes]')); + }; + + $scope.onClick = function (node) { + if (angular.isDefined($scope.tree) && angular.isFunction($scope.tree.on_click)) { + // We want to detach from Angular's digest cycle so we can + // independently measure the time for one cycle. + setTimeout( + function () { + $scope.tree.on_click(node); + }, 0 + ); + } + }; + + $scope.onSelect = function (node) { + if (angular.isDefined($scope.tree)) { + if (node !== $scope.tree.selected_node) { + $scope.tree.select_node(node); + } + + if (angular.isFunction($scope.tree.on_select)) { + setTimeout( + function () { + $scope.tree.on_select(node); + }, 0 + ); + } + } + }; + + var passedExpand, _clone; + $scope.toggleExpand = function (node, fnCallback) { + passedExpand = true; + if (angular.isFunction(fnCallback) && !fnCallback(node)) { + passedExpand = false; + } else if (angular.isFunction($scope.$callbacks.expand) && !$scope.$callbacks.expand(node)) { + passedExpand = false; + } + + if (passedExpand) { + if (node.__children__.length > 0) { + node.__expanded__ = !node.__expanded__; + } + } + }; + + + var _fnGetHash = function (node) { + return '#' + node.__parent__ + '#' + node[$scope.primary_key]; + }, + _fnSetHash = function (node) { + var _hashKey = _fnGetHash(node); + if (angular.isUndefinedOrNull(node.__hashKey__) || node.__hashKey__ !== _hashKey) { + node.__hashKey__ = _hashKey; + } + return node; + }; + $scope.getHash = _fnGetHash; + $scope.$callbacks = { + getHash: _fnGetHash, + setHash: _fnSetHash, + for_all_descendants: $scope.for_all_descendants, + /*expand: function (node) { + return true; + },*/ + accept: function (dragInfo, moveTo, isChanged) { + return $scope.dropEnabled === true; + }, + calsIndent: function (level, skipUnit, skipEdge) { + var unit = 0, + edge = skipEdge ? 0 : $scope.indent_plus; + if (!skipUnit) { + unit = $scope.indent_unit ? $scope.indent_unit : 'px'; + } + + if (level - 1 < 1) { + return edge + unit; + } else { + return $scope.indent * (level - 1) + edge + unit; + } + }, + droppable: function () { + return $scope.dropEnabled === true; + }, + draggable: function () { + return $scope.dragEnabled === true; + }, + beforeDrop: function (event) { + return true; + }, + changeKey: function (node) { + var _key = node.__uid__; + node.__uid__ = Math.random(); + if (node.__selected__) { + delete node.__selected__; + } + + if ($scope.primary_key !== '__uid__') { + _key = '' + node[$scope.primary_key]; + _key = _key.replace(/_#.+$/g, '') + '_#' + node.__uid__; + + node[$scope.primary_key] = _key; + } + // delete(node.__hashKey__); + }, + clone: function (node, _this) { + _clone = angular.copy(node); + this.for_all_descendants(_clone, this.changeKey); + return _clone; + }, + remove: function (node, parent, _this, delayReload) { + var temp = parent.splice(node.__index__, 1)[0]; + if (!delayReload) { + $scope.reload_data(); + } + return temp; + }, + clearInfo: function (node) { + delete node.__inited__; + delete node.__visible__; + + // always changed after call reload_data + //delete node.__hashKey__; + }, + add: function (node, pos, parent, _this) { + // clearInfo + this.for_all_descendants(node, this.clearInfo); + if (parent) { + if (parent.length > -1) { + if (pos > -1) { + parent.splice(pos, 0, node); + } else { + // todo If children need load crazy + parent.push(node); + } + } else { + parent.push(node); + } + } + } + }; + + $scope.deleteScope = function (scope, node) { + var _hash = node.__hashKey__; + if ($scope.$globals[_hash] && $scope.$globals[_hash] === scope) { + delete $scope.$globals[_hash]; + } + }; + + $scope.setScope = function (scope, node) { + var _hash = node.__hashKey__; + if ($scope.$globals[_hash] !== scope) { + $scope.$globals[_hash] = scope; + } + }; + + $scope.getScope = function (node) { + if (node) { + var _hash = node.__hashKey__; + //var _hash = typeof node === 'string' ? node : node.__hashKey__; + return $scope.$globals[_hash]; + } + return $scope; + }; + + if ($attrs.enableDrag || $attrs.enableDrop) { + $scope.placeElm = null; + // $scope.dragBorder = 30; + $scope.dragEnabled = null; + $scope.dropEnabled = null; + $scope.horizontal = null; + + if ($attrs.enableDrag) { + + $scope.dragDelay = 0; + $scope.enabledMove = true; + $scope.statusMove = true; + $scope.enabledHotkey = false; + $scope.enabledCollapse = null; + $scope.statusElm = null; + $scope.dragging = null; + + angular.extend( + $scope.$callbacks, { + beforeDrag: function (scopeDrag) { + return true; + }, + dragStop: function (info, passed) { + if (!info || !info.changed && info.drag.enabledMove || !passed) { + return null; + } + + info.target.reload_data(); + + if (info.target !== info.drag && info.drag.enabledMove) { + info.drag.reload_data(); + } + }, + dropped: function (info, pass) { + if (!info) { + return null; + } + + var _node = info.node, + _nodeAdd = null, + _move = info.move, + _parent = null, + _parentRemove = info.parent || info.drag.treeData, + _parentAdd = _move.parent || info.target.treeData, + isMove = info.drag.enabledMove; + + if (!info.changed && isMove) { + return false; + } + + if (info.target.$callbacks.accept(info, info.move, info.changed)) { + if (isMove) { + _parent = _parentRemove; + if (angular.isDefined(_parent.__children__)) { + _parent = _parent.__children__; + } + + _nodeAdd = info.drag.$callbacks.remove( + _node, + _parent, + info.drag.$callbacks, + true // delay reload + ); + } else { + _nodeAdd = info.drag.$callbacks.clone(_node, info.drag.$callbacks); + } + + // if node dragging change index in sample node parent + // and index node decrement + if (isMove && + info.drag === info.target && + _parentRemove === _parentAdd && + _move.pos >= info.node.__index__) { + _move.pos--; + } + + _parent = _parentAdd; + if (_parent.__children__) { + _parent = _parent.__children__; + } + + info.target.$callbacks.add( + _nodeAdd, + _move.pos, + _parent, + info.drag.$callbacks + ); + + return true; + } + + return false; + }, + dragStart: function (event) { + }, + dragMove: function (event) { + } + } + ); + + $scope.setDragging = function (dragInfo) { + $scope.dragging = dragInfo; + }; + + $scope.enableMove = function (val) { + if (typeof val === 'boolean') { + $scope.enabledMove = val; + } else { + $scope.enabledMove = true; + } + }; + + if ($attrs.enableStatus) { + $scope.enabledStatus = false; + + $scope.hideStatus = function () { + if ($scope.statusElm) { + $scope.statusElm.addClass($scope.$class.hidden); + } + }; + + $scope.refreshStatus = function () { + if (!$scope.dragging) { + return; + } + + if ($scope.enabledStatus) { + var statusElmOld = $scope.statusElm; + if ($scope.enabledMove) { + $scope.statusElm = angular.element($TreeDnDTemplate.getMove($scope)); + } else { + $scope.statusElm = angular.element($TreeDnDTemplate.getCopy($scope)); + } + + if (statusElmOld !== $scope.statusElm) { + if (statusElmOld) { + $scope.statusElm.attr('class', statusElmOld.attr('class')); + $scope.statusElm.attr('style', statusElmOld.attr('style')); + statusElmOld.remove(); + } + $document.find('body').append($scope.statusElm); + + } + + $scope.statusElm.removeClass($scope.$class.hidden); + } + }; + + $scope.setPositionStatus = function (e) { + if ($scope.statusElm) { + $scope.statusElm.css( + { + 'left': e.pageX + 10 + 'px', + 'top': e.pageY + 15 + 'px', + 'z-index': 9999 + } + ); + $scope.statusElm.addClass($scope.$class.status); + } + }; + } + } + + $scope.targeting = false; + + $scope.getPrevSibling = function (node) { + if (node && node.__index__ > 0) { + var _parent, _index = node.__index__ - 1; + + if (angular.isDefined(node.__parent_real__)) { + _parent = $scope.tree_nodes[node.__parent_real__]; + return _parent.__children__[_index]; + } + return $scope.treeData[_index]; + + } + return null; + }; + + $scope.getNode = function (index) { + if (angular.isUndefinedOrNull(index)) { + return null; + } + return $scope.tree_nodes[index]; + }; + + $scope.initPlace = function (element, dragElm) { + + if (!$scope.placeElm) { + if ($scope.isTable) { + $scope.placeElm = angular.element($window.document.createElement('tr')); + var _len_down = $scope.colDefinitions.length; + $scope.placeElm.append( + angular.element($window.document.createElement('td')) + .addClass($scope.$class.empty) + .addClass('indented') + .addClass($scope.$class.place) + ); + while (_len_down-- > 0) { + $scope.placeElm.append( + angular.element($window.document.createElement('td')) + .addClass($scope.$class.empty) + .addClass($scope.$class.place) + ); + } + } else { + $scope.placeElm = angular.element($window.document.createElement('li')) + .addClass($scope.$class.empty) + .addClass($scope.$class.place); + } + + } + + if (dragElm) { + $scope.placeElm.css('height', $TreeDnDHelper.height(dragElm) + 'px'); + } + + if (element) { + element[0].parentNode.insertBefore($scope.placeElm[0], element[0]); + } else { + $scope.getElementChilds().append($scope.placeElm); + } + + return $scope.placeElm; + }; + + $scope.hidePlace = function () { + if ($scope.placeElm) { + $scope.placeElm.addClass($scope.$class.hidden); + } + }; + + $scope.showPlace = function () { + if ($scope.placeElm) { + $scope.placeElm.removeClass($scope.$class.hidden); + } + }; + + $scope.getScopeTree = function () { + return $scope; + }; + + } + + $scope.$safeApply = $safeApply; + + + $scope.hiddenChild = function fnHiddenChild(node, parent) { + var nodeScope = $scope.getScope(node); + if (nodeScope) { + if (parent && parent.__expanded__ && parent.__visible__) { + nodeScope.$element.removeClass($scope.$class.hidden); + node.__visible__ = true; + } else { + nodeScope.$element.addClass($scope.$class.hidden); + node.__visible__ = false; + } + } else { + // show node & init scope + if (parent && parent.__expanded__ && parent.__visible__) { + node.__visible__ = true; + } else { + node.__visible__ = false; + } + } + + // skip all child hiding... if not expaned + return node.__expanded__ === false; + } + var _fnInitFilter, + _fnInitOrderBy, + _fnGetControl, + _defaultFilterOption = { + showParent: true, + showChild: false, + beginAnd: true + }, + tree, + _watches = [ + [ + 'enableDrag', [ + ['boolean', 'enableStatus', null, 'enabledStatus'], + ['boolean', 'enableMove', null, 'enabledMove'], + ['number', 'dragDelay', 0, null, 0], + ['boolean', 'enableCollapse', null, 'enabledCollapse'], + [ + 'boolean', 'enableHotkey', null, 'enabledHotkey', null, function (isHotkey) { + if (isHotkey) { + $scope.enabledMove = false; + } else { + $scope.enabledMove = $scope.statusMove; + } + }] + ]], + [ + ['enableDrag', 'enableStatus'], [ + [ + 'string', 'templateCopy', $attrs.templateCopy, 'templateCopy', null, + function (_url) { + if (_url && $templateCache.get(_url)) { + $TreeDnDTemplate.setCopy(_url, $scope); + } + }], + [ + 'string', 'templateMove', $attrs.templateMove, 'templateMove', null, + function (_url) { + if (_url && $templateCache.get(_url)) { + $TreeDnDTemplate.setMove(_url, $scope); + } + }] + ]], + [ + [['enableDrag', 'enableDrop']], [ + ['number', 'dragBorder', 30, 'dragBorder', 30]] + ], + [ + '*', [ + ['boolean', 'treeTable', true, 'treeTable', null], + ['boolean', 'horizontal'], + [ + 'callback', 'treeClass', function (val) { + switch (typeof val) { + case 'string': + $scope.$tree_class = val; + break; + case 'object': + angular.extend($scope.$class, val); + $scope.$tree_class = $scope.$class.tree; + break; + default: + $scope.$tree_class = $attrs.treeClass; + break; + } + }, 'treeClass', function () { + $scope.$tree_class = $scope.$class.tree + ' table'; + }, null, function () { + if (/^(\s+[\w\-]+){2,}$/g.test(' ' + $attrs.treeClass)) { + $scope.$tree_class = $attrs.treeClass.trim(); + return true; + } + }], + [ + ['object', 'string'], 'expandOn', getExpandOn, 'expandingProperty', getExpandOn, + function (expandOn) { + if (angular.isUndefinedOrNull(expandOn)) { + $scope.expandingProperty = $attrs.expandOn; + } + }], + [ + 'object', 'treeControl', angular.isDefined($scope.tree) ? $scope.tree : {}, + 'tree', null, function ($tree) { + + if (!angular.isFunction(_fnGetControl)) { + _fnGetControl = $TreeDnDPlugin('$TreeDnDControl'); + } + + if (angular.isFunction(_fnGetControl)) { + tree = angular.extend( + $tree, + _fnGetControl($scope) + ); + } + }], + [ + ['array', 'object'], 'columnDefs', getColDefs, 'colDefinitions', getColDefs, + function (colDefs) { + if (angular.isUndefinedOrNull(colDefs) || !angular.isArray(colDefs)) { + $scope.colDefinitions = getColDefs(); + } + }], + [['object', 'string', 'array', 'function'], 'orderBy', $attrs.orderBy], + [ + ['object', 'array'], 'filter', null, 'filter', null, function (filters) { + var _passed = false; + if (angular.isDefined(filters) && !angular.isArray(filters)) { + var _keysF = Object.keys(filters), + _lenF = _keysF.length, _iF; + + if (_lenF > 0) { + for (_iF = 0; _iF < _lenF; _iF++) { + + if (typeof filters[_keysF[_iF]] === 'string' && + filters[_keysF[_iF]].length === 0) { + continue; + } + _passed = true; + break; + } + } + } + + $scope.enabledFilter = _passed; + reload_data(); + }], + [ + 'object', 'filterOptions', _defaultFilterOption, 'filterOptions', + _defaultFilterOption, function (option) { + if (typeof option === 'object') { + $scope.filterOptions = angular.extend(_defaultFilterOption, option); + } + }], + ['string', 'primaryKey', $attrs.primaryKey, 'primary_key', '__uid__'], + ['string', 'indentUnit', $attrs.indentUnit, 'indent_unit'], + ['number', 'indent', 30, null, 30], + ['number', 'indentPlus', 20, null, 20], + [ + 'null', 'callbacks', + function (optCallbacks) { + angular.forEach( + optCallbacks, function (value, key) { + if (typeof value === 'function') { + if ($scope.$callbacks[key]) { + $scope.$callbacks[key] = value; + } + } + } + ); + return $scope.$callbacks; + }, + '$callbacks' + ], + [ + 'number', 'expandLevel', 3, 'expandLevel', 3, function () { + reload_data(); + }], + ['number', 'treeLimit', 100, '$TreeLimit', 100], + ['boolean', 'enableDrag', null, 'dragEnabled'], + ['boolean', 'enableDrop', null, 'dropEnabled'] + ]] + ], + w, lenW = _watches.length, + i, len, + _curW, + _typeW, _nameW, _defaultW, _scopeW, _NotW, _AfterW, _BeforeW, + + // debounce reload_Data; + timeReloadData, tmpTreeData; + + for (w = 0; w < lenW; w++) { + // skip if not exist + if (!check_exist_attr($attrs, _watches[w][0], true)) { + continue; + } + _curW = _watches[w][1]; + for (i = 0, len = _curW.length; i < len; i++) { + _typeW = _curW[i][0]; + _nameW = _curW[i][1]; + _defaultW = _curW[i][2]; + _scopeW = _curW[i][3]; + _NotW = _curW[i][4]; + _AfterW = _curW[i][5]; + _BeforeW = _curW[i][6]; + generateWatch(_typeW, _nameW, _defaultW, _scopeW, _NotW, _AfterW, _BeforeW); + } + } + + if ($attrs.treeData) { + $scope.$watch( + $attrs.treeData, function (val) { + if (angular.equals(val, $scope.treeData)) { + return; + } + + tmpTreeData = val; + if (angular.isUndefinedOrNull(timeReloadData)) { + timeReloadData = $timeout(timeLoadData, 350); + } + }, true + ); + } + + function timeLoadData() { + $scope.treeData = tmpTreeData; + reload_data(); + timeReloadData = null; + } + + $scope.updateLimit = function updateLimit() { + //console.log('Call fn UpdateLimit'); + $scope.$TreeLimit += 50; + }; + + $scope.reload_data = reload_data; + + function check_exist_attr(attrs, existAttr, isAnd) { + if (angular.isUndefinedOrNull(existAttr)) { + return false; + } + + if (existAttr === '*' || !angular.isUndefined(attrs[existAttr])) { + return true; + } + + if (angular.isArray(existAttr)) { + return for_each_attrs(attrs, existAttr, isAnd); + } + } + + function for_each_attrs(attrs, exist, isAnd) { + var i, len = exist.length, passed = false; + + if (len === 0) { + return null; + } + for (i = 0; i < len; i++) { + if (check_exist_attr(attrs, exist[i], !isAnd)) { + passed = true; + if (!isAnd) { + return true; + } + } else { + if (isAnd) { + return false; + } + } + } + + return passed; + } + + function generateWatch(type, nameAttr, valDefault, nameScope, fnNotExist, fnAfter, + fnBefore + ) { + nameScope = nameScope || nameAttr; + if (typeof type === 'string' || angular.isArray(type)) { + if (angular.isFunction(fnBefore) && fnBefore()) { + return;//jmp + } + if (typeof $attrs[nameAttr] === 'string') { + $scope.$watch( + $attrs[nameAttr], function (val) { + if (typeof type === 'string' && typeof val === type || + angular.isArray(type) && type.indexOf(typeof val) > -1 + ) { + $scope[nameScope] = val; + } else { + if (angular.isFunction(valDefault)) { + $scope[nameScope] = valDefault(val); + } else { + $scope[nameScope] = valDefault; + } + } + + if (angular.isFunction(fnAfter)) { + fnAfter($scope[nameScope], $scope); + } + }, true + ); + } else { + + if (angular.isFunction(fnNotExist)) { + $scope[nameScope] = fnNotExist(); + } else if (!angular.isUndefined(fnNotExist)) { + $scope[nameScope] = fnNotExist; + } + } + } + } + + function $safeApply(fn) { + var phase = this.$root.$$phase; + if (phase === '$apply' || phase === '$digest') { + if (fn && typeof fn === 'function') { + fn(); + } + } else { + this.$apply(fn); + } + } + + function getExpandOn() { + if ($scope.treeData && $scope.treeData.length) { + var _firstNode = $scope.treeData[0], _keys = Object.keys(_firstNode), + _regex = new RegExp('^__([a-zA-Z0-9_\-]*)__$'), + _len, + i; + // Auto get first field with type is string; + for (i = 0, _len = _keys.length; i < _len; i++) { + if (typeof _firstNode[_keys[i]] === 'string' && !_regex.test(_keys[i])) { + $scope.expandingProperty = _keys[i]; + return; + } + } + + // Auto get first + if (angular.isUndefinedOrNull($scope.expandingProperty)) { + $scope.expandingProperty = _keys[0]; + } + + } + } + + function getColDefs() { + // Auto get Defs except attribute __level__ .... + if ($scope.treeData.length) { + var _col_defs = [], _firstNode = $scope.treeData[0], + _regex = new RegExp('(^__([a-zA-Z0-9_\-]*)__$|^' + $scope.expandingProperty + '$)'), + _keys = Object.keys(_firstNode), + i, _len; + // Auto get first field with type is string; + for (i = 0, _len = _keys.length; i < _len; i++) { + if (typeof _firstNode[_keys[i]] === 'string' && !_regex.test(_keys[i])) { + _col_defs.push( + { + field: _keys[i] + } + ); + } + } + $scope.colDefinitions = _col_defs; + } + } + + function do_f(root, node, parent, parent_real, level, visible, index) { + + if(typeof node !== 'object'){ + return 0; + } + + var _i, _len, _icon, _index_real, _dept, _hashKey; + if (!angular.isArray(node.__children__)) { + node.__children__ = []; + } + + node.__parent_real__ = parent_real; + node.__parent__ = parent; + _len = node.__children__.length; + + if (angular.isUndefinedOrNull(node.__expanded__) && _len > 0) { + node.__expanded__ = level < $scope.expandLevel; + } + + if (_len === 0) { + _icon = -1; + } else { + if (node.__expanded__) { + _icon = 1; + } else { + _icon = 0; + } + } + + // Insert item vertically + _index_real = root.length; + node.__index__ = index; + node.__index_real__ = _index_real; + node.__level__ = level; + node.__icon__ = _icon; + node.__icon_class__ = $scope.$class.icon[_icon]; + node.__visible__ = !!visible; + + if (angular.isUndefinedOrNull(node.__uid__)) { + node.__uid__ = '' + Math.random(); + } + + _hashKey = $scope.getHash(node); + + if (angular.isUndefinedOrNull(node.__hashKey__) || node.__hashKey__ !== _hashKey) { + node.__hashKey__ = _hashKey; + } + + root.push(node); + + // Check node children + _dept = 1; + if (_len > 0) { + for (_i = 0; _i < _len; _i++) { + _dept += do_f( + root, + node.__children__[_i], + node[$scope.primary_key], + _index_real, + level + 1, + visible && node.__expanded__, + _i + ); + } + } + + node.__dept__ = _dept; + + return _dept; + } + + function init_data(data) { + + // clear memory + if (angular.isDefined($scope.tree_nodes)) { + delete $scope.tree_nodes; + } + + $scope.tree_nodes = data; + return data; + } + + function reload_data(oData) { + var _data, + _len, + _tree_nodes = []; + if (angular.isDefined(oData)) { + if (!angular.isArray(oData) || oData.length === 0) { + return init_data([]); + } else { + _data = oData; + } + } else if (!angular.isArray($scope.treeData) || $scope.treeData.length === 0) { + return init_data([]); + } else { + _data = $scope.treeData; + } + + if (!$attrs.expandOn) { + getExpandOn(); + } + + if (!$attrs.columnDefs) { + getColDefs(); + } + + if (angular.isDefined($scope.orderBy)) { + if (!angular.isFunction(_fnInitOrderBy)) { + _fnInitOrderBy = $TreeDnDPlugin('$TreeDnDOrderBy'); + } + + if (angular.isFunction(_fnInitOrderBy)) { + _data = _fnInitOrderBy(_data, $scope.orderBy); + } + } + + if (angular.isDefined($scope.filter)) { + if (!angular.isFunction(_fnInitFilter)) { + _fnInitFilter = $TreeDnDPlugin('$TreeDnDFilter'); + } + + if (angular.isFunction(_fnInitFilter)) { + _data = _fnInitFilter(_data, $scope.filter, $scope.filterOptions); + } + } + + _len = _data.length; + if (_len > 0) { + var _i, + _deptTotal = 0; + + for (_i = 0; _i < _len; _i++) { + _deptTotal += do_f(_tree_nodes, _data[_i], null, null, 1, true, _i); + } + + } + + init_data(_tree_nodes); + + return _tree_nodes; + } + } + + function fnCompile(tElement) { + + var $_Template = '', + _element = tElement.html().trim(); + + if (_element.length > 0) { + $_Template = _element; + tElement.html(''); + } + + return function fnPost(scope, element, attrs) { + + if (attrs.enableDrag) { + var _fnInitDrag = $TreeDnDPlugin('$TreeDnDDrag'); + if (angular.isFunction(_fnInitDrag)) { + _fnInitDrag(scope, element, $window, $document); + } + } + + // kick out $digest + element.ready(function () { + // apply Template + function checkTreeTable(template, scope) { + var elemNode = template[0].querySelector('[tree-dnd-node]'), + attrInclude; + + scope.isTable = null; + if (elemNode) { + elemNode = angular.element(elemNode); + attrInclude = elemNode.attr('ng-include'); + } else { + return; + } + + if (attrInclude) { + var treeInclude = $parse(attrInclude)(scope) || attrInclude; + if (typeof treeInclude === 'string') { + return $http.get( + treeInclude, + {cache: $templateCache} + ).success( + function (data) { + data = data.trim(); + //scope.templateNode = data; + var tempDiv = document.createElement('div'); + tempDiv.innerHTML = data; + tempDiv = angular.element(tempDiv); + scope.isTable = !tempDiv[0].querySelector('[tree-dnd-nodes]'); + } + ); + } + } else { + scope.isTable = !elemNode[0].querySelector('[tree-dnd-nodes]'); + //scope.templateNode = elemNode.html(); + } + $TreeDnDViewport.setTemplate(scope, scope.templateNode); + //elemNode.html(''); + } + + //scope.$watch(tableDataLoaded, transformTable); + /* + function tableDataLoaded(elem) { + // first cell in the tbody exists when data is loaded but doesn't have a width + // until after the table is transformed + var firstCell = elem.querySelector('tbody tr:first-child td:first-child'); + return firstCell && !firstCell.style.width; + } + + function transformTable(elem, attrs) { + // reset display styles so column widths are correct when measured below + angular.element(elem.querySelectorAll('thead, tbody, tfoot')).css('display', ''); + + // wrap in $timeout to give table a chance to finish rendering + $timeout(function () { + // set widths of columns + angular.forEach(elem.querySelectorAll('tr:first-child th'), function (thElem, i) { + + var tdElems = elem.querySelector('tbody tr:first-child td:nth-child(' + (i + 1) + ')'); + var tfElems = elem.querySelector('tfoot tr:first-child td:nth-child(' + (i + 1) + ')'); + + var columnWidth = tdElems ? tdElems.offsetWidth : thElem.offsetWidth; + if (tdElems) { + tdElems.style.width = columnWidth + 'px'; + } + if (thElem) { + thElem.style.width = columnWidth + 'px'; + } + if (tfElems) { + tfElems.style.width = columnWidth + 'px'; + } + }); + + // set css styles on thead and tbody + angular.element(elem.querySelectorAll('thead, tfoot')).css('display', 'block'); + + angular.element(elem.querySelectorAll('tbody')).css({ + 'display': 'block', + 'height': attrs.tableHeight || 'inherit', + 'overflow': 'auto' + }); + + // reduce width of last column by width of scrollbar + var tbody = elem.querySelector('tbody'); + var scrollBarWidth = tbody.offsetWidth - tbody.clientWidth; + if (scrollBarWidth > 0) { + // for some reason trimming the width by 2px lines everything up better + scrollBarWidth -= 2; + var lastColumn = elem.querySelector('tbody tr:first-child td:last-child'); + lastColumn.style.width = lastColumn.offsetWidth - scrollBarWidth + 'px'; + } + }); + }*/ + var promiseCheck; + if ($_Template.length > 0) { + promiseCheck = checkTreeTable(angular.element($_Template.trim()), scope); + if (typeof promiseCheck === 'object') { + promiseCheck.then(function () { + element.append($compile($_Template)(scope)); + }); + } else { + element.append($compile($_Template)(scope)); + } + } else { + $http.get( + attrs.templateUrl || $TreeDnDTemplate.getPath(), + {cache: $templateCache} + ).success( + function (data) { + data = angular.element(data.trim()); + promiseCheck = checkTreeTable(data, scope); + if (typeof promiseCheck === 'object') { + promiseCheck.then(function () { + element.append($compile(data)(scope)); + }); + } else { + element.append($compile(data)(scope)); + } + } + ); + } + }) + }; + } +} + + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDFilter', [ + '$filter', function ($filter) { + return fnInitFilter; + + function for_all_descendants(options, node, fieldChild, fnBefore, fnAfter, parentPassed) { + if (!angular.isFunction(fnBefore)) { + return null; + } + + var _i, _len, _nodes, + _nodePassed = fnBefore(options, node), + _childPassed = false, + _filter_index = options.filter_index; + + if (angular.isDefined(node[fieldChild])) { + _nodes = node[fieldChild]; + _len = _nodes.length; + options.filter_index = 0; + for (_i = 0; _i < _len; _i++) { + _childPassed = for_all_descendants( + options, + _nodes[_i], + fieldChild, + fnBefore, + fnAfter, + _nodePassed || parentPassed + ) || _childPassed; + } + + // restore filter_index of node + options.filter_index = _filter_index; + } + + if (angular.isFunction(fnAfter)) { + fnAfter(options, node, _nodePassed === true, _childPassed === true, parentPassed === true); + } + + return _nodePassed || _childPassed; + } + + /** + * Check data with callback + * @param {string|object|function|regex} callback + * @param {*} data + * @returns {null|boolean} + * @private + */ + function _fnCheck(callback, data) { + if (angular.isUndefinedOrNull(data) || angular.isArray(data)) { + return null; + } + + if (angular.isFunction(callback)) { + return callback(data, $filter); + } else { + if (typeof callback === 'boolean') { + data = !!data; + return data === callback; + } else if (angular.isDefined(callback)) { + try { + var _regex = new RegExp(callback); + return _regex.test(data); + } + catch (err) { + if (typeof data === 'string') { + return data.indexOf(callback) > -1; + } else { + return null; + } + } + } else { + return null; + } + } + } + + /** + * `fnProcess` to call `_fnCheck`. If `condition` is `array` then call `for_each_filter` + * else will call `_fnCheck`. Specical `condition.field` is `_$` then apply `condition.callback` for all field, if have `field` invaild then `return true`. + * + * @param node + * @param condition + * @param isAnd + * @returns {null|boolean} + * @private + */ + function _fnProccess(node, condition, isAnd) { + if (angular.isArray(condition)) { + return for_each_filter(node, condition, isAnd); + } else { + var _key = condition.field, + _callback = condition.callback, + _iO, _keysO, _lenO; + + if (_key === '_$') { + _keysO = Object.keys(node); + _lenO = _keysO.length; + for (_iO = 0; _iO < _lenO; _iO++) { + if (_fnCheck(_callback, node[_keysO[_iO]])) { + return true; + } + } + } else if (angular.isDefined(node[_key])) { + return _fnCheck(_callback, node[_key]); + } + } + return null; + } + + /** + * + * @param {object} node + * @param {array} conditions Array `conditions` + * @param {boolean} isAnd check with condition `And`, if `And` then `return false` when all `false` + * @returns {null|boolean} + */ + function for_each_filter(node, conditions, isAnd) { + var i, len = conditions.length || 0, passed = false; + if (len === 0) { + return null; + } + + for (i = 0; i < len; i++) { + if (_fnProccess(node, conditions[i], !isAnd)) { + passed = true; + // if condition `or` then return; + if (!isAnd) { + return true; + } + } else { + + // if condition `and` and result in fnProccess = false then return; + if (isAnd) { + return false; + } + } + } + + return passed; + } + + /** + * Will call _fnAfter to clear data no need + * @param {object} options + * @param {object} node + * @param {boolean} isNodePassed + * @param {boolean} isChildPassed + * @param {boolean} isParentPassed + * @private + */ + function _fnAfter(options, node, isNodePassed, isChildPassed, isParentPassed) { + if (isNodePassed === true) { + node.__filtered__ = true; + node.__filtered_visible__ = true; + node.__filtered_index__ = options.filter_index++; + return; //jmp + } else if (isChildPassed === true && options.showParent === true + || isParentPassed === true && options.showChild === true) { + node.__filtered__ = false; + node.__filtered_visible__ = true; + node.__filtered_index__ = options.filter_index++; + return; //jmp + } + + // remove attr __filtered__ + delete node.__filtered__; + delete node.__filtered_visible__; + delete node.__filtered_index__; + } + + /** + * `fnBefore` will called when `for_all_descendants` of `node` checking. + * If `filter` empty then return `true` else result of function `_fnProccess` {@see _fnProccess} + * + * @param {object} options + * @param {object} node + * @returns {null|boolean} + * @private + */ + function _fnBefore(options, node) { + if (options.filter.length === 0) { + return true; + } else { + return _fnProccess(node, options.filter, options.beginAnd || false); + } + } + + /** + * `fnBeforeClear` will called when `for_all_descendants` of `node` checking. + * Alway false to Clear Filter empty + * + * @param {object} options + * @param {object} node + * @returns {null|boolean} + * @private + */ + function _fnBeforeClear(options, node) { + return false; + } + + /** + * `_fnConvert` to convert `filter` `object` to `array` invaild. + * + * @param {object|array} filters + * @returns {array} Instead of `filter` or new array invaild *(converted from filter)* + * @private + */ + function _fnConvert(filters) { + var _iF, _lenF, _keysF, + _filter, + _state; + // convert filter object to array filter + if (angular.isObject(filters) && !angular.isArray(filters)) { + _keysF = Object.keys(filters); + _lenF = _keysF.length; + _filter = []; + + if (_lenF > 0) { + for (_iF = 0; _iF < _lenF; _iF++) { + + if (typeof filters[_keysF[_iF]] === 'string' && filters[_keysF[_iF]].length === 0) { + continue; + } else if (angular.isArray(filters[_keysF[_iF]])) { + _state = filters[_keysF[_iF]]; + } else if (angular.isObject(filters[_keysF[_iF]])) { + _state = _fnConvert(filters[_keysF[_iF]]); + } else { + _state = { + field: _keysF[_iF], + callback: filters[_keysF[_iF]] + }; + } + _filter.push(_state); + } + } + _state = null; + return _filter; + } + else { + return filters; + } + } + + /** + * `fnInitFilter` function is constructor of service `$TreeDnDFilter`. + * @constructor + * @param {object|array} treeData + * @param {object|array} filters + * @param {object} options + * @param {string} keyChild + * @returns {array} Return `treeData` or `treeData` with `filter` + * @private + */ + function fnInitFilter(treeData, filters, options, keyChild) { + if (!angular.isArray(treeData) + || treeData.length === 0) { + return treeData; + } + + var _i, _len, + _filter; + + _filter = _fnConvert(filters); + if (!(angular.isArray(_filter) || angular.isObject(_filter)) + || _filter.length === 0) { + for (_i = 0, _len = treeData.length; _i < _len; _i++) { + for_all_descendants( + options, + treeData[_i], + keyChild || '__children__', + _fnBeforeClear, _fnAfter + ); + } + return treeData; + } + + options.filter = _filter; + options.filter_index = 0; + for (_i = 0, _len = treeData.length; _i < _len; _i++) { + for_all_descendants( + options, + treeData[_i], + keyChild || '__children__', + _fnBefore, _fnAfter + ); + } + + return treeData; + } + + }] +); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDOrderBy', [ + '$filter', function ($filter) { + var _fnOrderBy = $filter('orderBy'), + for_all_descendants = function for_all_descendants(options, node, name, fnOrderBy) { + var _i, _len, _nodes; + + if (angular.isDefined(node[name])) { + _nodes = node[name]; + _len = _nodes.length; + // OrderBy children + for (_i = 0; _i < _len; _i++) { + _nodes[_i] = for_all_descendants(options, _nodes[_i], name, fnOrderBy); + } + + node[name] = fnOrderBy(node[name], options); + } + return node; + }, + _fnOrder = function _fnOrder(list, orderBy) { + return _fnOrderBy(list, orderBy); + }, + _fnMain = function _fnMain(treeData, orderBy) { + if (!angular.isArray(treeData) + || treeData.length === 0 + || !(angular.isArray(orderBy) || angular.isObject(orderBy) || angular.isString(orderBy) || angular.isFunction(orderBy)) + || orderBy.length === 0 && !angular.isFunction(orderBy)) { + return treeData; + } + + var _i, _len; + + for (_i = 0, _len = treeData.length; _i < _len; _i++) { + treeData[_i] = for_all_descendants( + orderBy, + treeData[_i], + '__children__', + _fnOrder + ); + } + + return _fnOrder(treeData, orderBy); + }; + + return _fnMain; + }] +); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDConvert', function () { + var _$initConvert = { + line2tree: function (data, primaryKey, parentKey, callback) { + callback = typeof callback === 'function' ? callback : function () { + }; + if (!data || data.length === 0 || !primaryKey || !parentKey) { + return []; + } + var tree = [], + rootIds = [], + item = data[0], + _primary = item[primaryKey], + treeObjs = {}, + parentId, parent, + len = data.length, + i = 0; + while (i < len) { + item = data[i++]; + callback(item); + _primary = item[primaryKey]; + treeObjs[_primary] = item; + } + i = 0; + while (i < len) { + item = data[i++]; + callback(item); + _primary = item[primaryKey]; + treeObjs[_primary] = item; + parentId = item[parentKey]; + if (parentId) { + parent = treeObjs[parentId]; + if (parent) { + if (parent.__children__) { + parent.__children__.push(item); + } else { + parent.__children__ = [item]; + } + } + } else { + rootIds.push(_primary); + } + } + len = rootIds.length; + for (i = 0; i < len; i++) { + tree.push(treeObjs[rootIds[i]]); + } + return tree; + }, + tree2tree: function access_child(data, containKey, callback) { + callback = typeof callback === 'function' ? callback : function () { + }; + var _tree = [], + _i, + _len = data ? data.length : 0, + _copy, _child; + for (_i = 0; _i < _len; _i++) { + _copy = angular.copy(data[_i]); + callback(_copy); + if (angular.isArray(_copy[containKey]) && _copy[containKey].length > 0) { + _child = access_child(_copy[containKey], containKey, callback); + delete _copy[containKey]; + _copy.__children__ = _child; + } + _tree.push(_copy); + } + return _tree; + } + }; + + return _$initConvert; + } + ); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDHelper', [ + '$document', '$window', function ($document, $window) { + var _$helper = { + nodrag: function (targetElm) { + return typeof targetElm.attr('data-nodrag') !== 'undefined'; + }, + eventObj: function (e) { + var obj = e; + if (e.targetTouches !== undefined) { + obj = e.targetTouches.item(0); + } else if (e.originalEvent !== undefined && e.originalEvent.targetTouches !== undefined) { + obj = e.originalEvent.targetTouches.item(0); + } + return obj; + }, + dragInfo: function (scope) { + var _node = scope.getData(), + _tree = scope.getScopeTree(), + _parent = scope.getNode(_node.__parent_real__); + return { + node: _node, + parent: _parent, + move: { + parent: _parent, + pos: _node.__index__ + }, + scope: scope, + target: _tree, + drag: _tree, + drop: scope.getPrevSibling(_node), + changed: false + }; + }, + height: function (element) { + return element.prop('scrollHeight'); + }, + width: function (element) { + return element.prop('scrollWidth'); + }, + offset: function (element) { + var boundingClientRect = element[0].getBoundingClientRect(); + return { + width: element.prop('offsetWidth'), + height: element.prop('offsetHeight'), + top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop), + left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft) + }; + }, + positionStarted: function (e, target) { + var pos = {}; + pos.offsetX = e.pageX - this.offset(target).left; + pos.offsetY = e.pageY - this.offset(target).top; + pos.startX = pos.lastX = e.pageX; + pos.startY = pos.lastY = e.pageY; + pos.nowX = pos.nowY = pos.distX = pos.distY = pos.dirAx = 0; + pos.dirX = pos.dirY = pos.lastDirX = pos.lastDirY = pos.distAxX = pos.distAxY = 0; + return pos; + }, + positionMoved: function (e, pos, firstMoving) { + // mouse position last events + pos.lastX = pos.nowX; + pos.lastY = pos.nowY; + // mouse position this events + pos.nowX = e.pageX; + pos.nowY = e.pageY; + // distance mouse moved between events + pos.distX = pos.nowX - pos.lastX; + pos.distY = pos.nowY - pos.lastY; + // direction mouse was moving + pos.lastDirX = pos.dirX; + pos.lastDirY = pos.dirY; + // direction mouse is now moving (on both axis) + pos.dirX = pos.distX === 0 ? 0 : pos.distX > 0 ? 1 : -1; + pos.dirY = pos.distY === 0 ? 0 : pos.distY > 0 ? 1 : -1; + // axis mouse is now moving on + var newAx = Math.abs(pos.distX) > Math.abs(pos.distY) ? 1 : 0; + // do nothing on first move + if (firstMoving) { + pos.dirAx = newAx; + pos.moving = true; + return; + } + // calc distance moved on this axis (and direction) + if (pos.dirAx !== newAx) { + pos.distAxX = 0; + pos.distAxY = 0; + } else { + pos.distAxX += Math.abs(pos.distX); + if (pos.dirX !== 0 && pos.dirX !== pos.lastDirX) { + pos.distAxX = 0; + } + pos.distAxY += Math.abs(pos.distY); + if (pos.dirY !== 0 && pos.dirY !== pos.lastDirY) { + pos.distAxY = 0; + } + } + pos.dirAx = newAx; + }, + replaceIndent: function (scope, element, indent, attr) { + attr = attr || 'left'; + angular.element(element.children()[0]).css(attr, scope.$callbacks.calsIndent(indent)); + } + }; + return _$helper; + }] + ); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDPlugin', ['$injector', function ($injector) { + var _fnget = function (name) { + if (angular.isDefined($injector) && $injector.has(name)) { + return $injector.get(name); + } + return null; + }; + return _fnget; + }] + ); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDTemplate', [ + '$templateCache', function ($templateCache) { + var templatePath = 'template/TreeDnD/TreeDnD.html', + copyPath = 'template/TreeDnD/TreeDnDStatusCopy.html', + movePath = 'template/TreeDnD/TreeDnDStatusMove.html', + scopes = {}, + temp, + _$init = { + setMove: function (path, scope) { + if (!scopes[scope.$id]) { + scopes[scope.$id] = {}; + } + scopes[scope.$id].movePath = path; + }, + setCopy: function (path, scope) { + if (!scopes[scope.$id]) { + scopes[scope.$id] = {}; + } + scopes[scope.$id].copyPath = path; + }, + getPath: function () { + return templatePath; + }, + getCopy: function (scope) { + if (scopes[scope.$id] && scopes[scope.$id].copyPath) { + temp = $templateCache.get(scopes[scope.$id].copyPath); + if (temp) { + return temp; + } + } + return $templateCache.get(copyPath); + }, + getMove: function (scope) { + if (scopes[scope.$id] && scopes[scope.$id].movePath) { + temp = $templateCache.get(scopes[scope.$id].movePath); + if (temp) { + return temp; + } + } + return $templateCache.get(movePath); + } + }; + + return _$init; + }] + ); + +angular.module('ntt.TreeDnD') + .factory('$TreeDnDViewport', fnInitTreeDnDViewport); + +fnInitTreeDnDViewport.$inject = ['$window', '$document', '$timeout', '$q', '$compile']; + +function fnInitTreeDnDViewport($window, $document, $timeout, $q, $compile) { + + var viewport = null, + isUpdating = false, + isRender = false, + updateAgain = false, + viewportRect, + items = [], + nodeTemplate, + updateTimeout, + renderTime, + $initViewport = { + setViewport: setViewport, + getViewport: getViewport, + add: add, + setTemplate: setTemplate, + getItems: getItems, + updateDelayed: updateDelayed + }, + eWindow = angular.element($window); + + eWindow.on('load resize scroll', updateDelayed); + + return $initViewport; + + function update() { + + viewportRect = { + width: eWindow.prop('offsetWidth') || document.documentElement.clientWidth, + height: eWindow.prop('offsetHeight') || document.documentElement.clientHeight, + top: $document[0].body.scrollTop || $document[0].documentElement.scrollTop, + left: $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft + }; + + if (isUpdating || isRender) { + updateAgain = true; + return; + } + isUpdating = true; + + recursivePromise(); + } + + function recursivePromise() { + if (isRender) { + return; + } + + var number = number > 0 ? number : items.length, item; + + if (number > 0) { + item = items[0]; + + isRender = true; + renderTime = $timeout(function () { + //item.element.html(nodeTemplate); + //$compile(item.element.contents())(item.scope); + + items.splice(0, 1); + isRender = false; + number--; + $timeout.cancel(renderTime); + recursivePromise(); + }, 0); + + } else { + isUpdating = false; + if (updateAgain) { + updateAgain = false; + update(); + } + } + + } + + /** + * Check if a point is inside specified bounds + * @param x + * @param y + * @param bounds + * @returns {boolean} + */ + function pointIsInsideBounds(x, y, bounds) { + return x >= bounds.left && + y >= bounds.top && + x <= bounds.left + bounds.width && + y <= bounds.top + bounds.height; + } + + /** + * @name setViewport + * @desciption Set the viewport element + * @param element + */ + function setViewport(element) { + viewport = element; + } + + /** + * Return the current viewport + * @returns {*} + */ + function getViewport() { + return viewport; + } + + /** + * trigger an update + */ + function updateDelayed() { + $timeout.cancel(updateTimeout); + updateTimeout = $timeout(function () { + update(); + }, 0); + } + + /** + * Add listener for event + * @param element + * @param callback + */ + function add(scope, element) { + updateDelayed(); + items.push({ + element: element, + scope: scope + }); + } + + function setTemplate(scope, template) { + nodeTemplate = template; + } + + /** + * Get list of items + * @returns {Array} + */ + function getItems() { + return items; + } +} + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDDrag', [ + '$timeout', '$TreeDnDHelper', + function ($timeout, $TreeDnDHelper) { + function _fnPlaceHolder(e, $params) { + if ($params.placeElm) { + var _offset = $TreeDnDHelper.offset($params.placeElm); + if (_offset.top <= e.pageY && e.pageY <= _offset.top + _offset.height && + _offset.left <= e.pageX && e.pageX <= _offset.left + _offset.width + ) { + return true; + } + } + return false; + } + + function _fnDragStart(e, $params) { + if (!$params.hasTouch && (e.button === 2 || e.which === 3)) { + // disable right click + return; + } + if (e.uiTreeDragging || e.originalEvent && e.originalEvent.uiTreeDragging) { // event has already fired in other scope. + return; + } + // the element which is clicked. + var eventElm = angular.element(e.target), + eventScope = eventElm.scope(); + if (!eventScope || !eventScope.$type) { + return; + } + // if (eventScope.$type !== 'TreeDnDNode') { // Check if it is a node or a handle + // return; + // } + + if (eventScope.$type !== 'TreeDnDNodeHandle') { // If the node has a handle, then it should be clicked by the handle + return; + } + + var eventElmTagName = eventElm.prop('tagName').toLowerCase(), + dragScope, + _$scope = $params.$scope; + if (eventElmTagName === 'input' + || eventElmTagName === 'textarea' + || eventElmTagName === 'button' + || eventElmTagName === 'select') { // if it's a input or button, ignore it + return; + } + // check if it or it's parents has a 'data-nodrag' attribute + while (eventElm && eventElm[0] && eventElm[0] !== $params.element) { + if ($TreeDnDHelper.nodrag(eventElm)) { // if the node mark as `nodrag`, DONOT drag it. + return; + } + eventElm = eventElm.parent(); + } + + e.uiTreeDragging = true; // stop event bubbling + if (e.originalEvent) { + e.originalEvent.uiTreeDragging = true; + } + e.preventDefault(); + + dragScope = eventScope.getScopeNode(); + + $params.dragInfo = $TreeDnDHelper.dragInfo(dragScope); + + if (!_$scope.$callbacks.beforeDrag(dragScope, $params.dragInfo)) { + return; + } + + $params.firstMoving = true; + _$scope.setDragging($params.dragInfo); + + var eventObj = $TreeDnDHelper.eventObj(e); + $params.pos = $TreeDnDHelper.positionStarted(eventObj, dragScope.$element); + + if (dragScope.isTable) { + $params.dragElm = angular.element($params.$window.document.createElement('table')) + .addClass(_$scope.$class.tree) + .addClass(_$scope.$class.drag) + .addClass(_$scope.$tree_class); + } else { + $params.dragElm = angular.element($params.$window.document.createElement('ul')) + .addClass(_$scope.$class.drag) + .addClass('tree-dnd-nodes') + .addClass(_$scope.$tree_class); + } + + $params.dragElm.css( + { + 'width': $TreeDnDHelper.width(dragScope.$element) + 'px', + 'z-index': 9995 + } + ); + + $params.offsetEdge = 0; + var _width = $TreeDnDHelper.width(dragScope.$element), + _scope = dragScope, + _element = _scope.$element, + _clone, + _needCollapse = !!_$scope.enabledCollapse, + _copied = false, + _tbody, + _frag; + + if (_scope.isTable) { + $params.offsetEdge = $params.dragInfo.node.__level__ - 1; + _tbody = angular.element(document.createElement('tbody')); + _frag = angular.element(document.createDocumentFragment()); + + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element) { + if (!_copied) { + _clone = _element.clone(); + + $TreeDnDHelper.replaceIndent( + _$scope, + _clone, + _node.__level__ - $params.offsetEdge, + 'padding-left' + ); + + _frag.append(_clone); + + // skip all, just clone parent + if (_needCollapse) { + _copied = true; + } + + // hide if have status Move; + if (_$scope.enabledMove && _$scope.$class.hidden && + (!_parent || _node.__visible__ || _parent.__visible__ && _parent.__expanded__)) { + _element.addClass(_$scope.$class.hidden); + } + } + } + // skip children of node not expand. + return _copied || _node.__visible__ === false || _node.__expanded__ === false; + + }, null, !_needCollapse + ); + _tbody.append(_frag); + $params.dragElm.append(_tbody); + } else { + + _clone = _element.clone(); + if (_needCollapse) { + _clone[0].querySelector('[tree-dnd-nodes]').remove(); + } + + // hide if have status Move; + $params.dragElm.append(_clone); + if (_$scope.enabledMove && _$scope.$class.hidden) { + _element.addClass(_$scope.$class.hidden); + } + } + + $params.dragElm.css( + { + 'left': eventObj.pageX - $params.pos.offsetX + _$scope.$callbacks.calsIndent( + $params.offsetEdge + 1, + true, + true + ) + 'px', + 'top': eventObj.pageY - $params.pos.offsetY + 'px' + } + ); + // moving item with descendant + $params.$document.find('body').append($params.dragElm); + if (_$scope.$callbacks.droppable()) { + $params.placeElm = _$scope.initPlace(dragScope.$element, $params.dragElm); + + if (dragScope.isTable) { + $TreeDnDHelper.replaceIndent(_$scope, $params.placeElm, $params.dragInfo.node.__level__); + } + + $params.placeElm.css('width', _width); + } + + _$scope.showPlace(); + _$scope.targeting = true; + + if (_$scope.enabledStatus) { + _$scope.refreshStatus(); + _$scope.setPositionStatus(e); + } + + angular.element($params.$document).bind('touchend', $params.dragEndEvent); + angular.element($params.$document).bind('touchcancel', $params.dragEndEvent); + angular.element($params.$document).bind('touchmove', $params.dragMoveEvent); + angular.element($params.$document).bind('mouseup', $params.dragEndEvent); + angular.element($params.$document).bind('mousemove', $params.dragMoveEvent); + angular.element($params.$document).bind('mouseleave', $params.dragCancelEvent); + + $params.document_height = Math.max( + $params.body.scrollHeight, + $params.body.offsetHeight, + $params.html.clientHeight, + $params.html.scrollHeight, + $params.html.offsetHeight + ); + + $params.document_width = Math.max( + $params.body.scrollWidth, + $params.body.offsetWidth, + $params.html.clientWidth, + $params.html.scrollWidth, + $params.html.offsetWidth + ); + } + + function _fnDragMove(e, $params) { + var _$scope = $params.$scope; + if (!$params.dragStarted) { + if (!$params.dragDelaying) { + $params.dragStarted = true; + _$scope.$safeApply( + function () { + _$scope.$callbacks.dragStart($params.dragInfo); + } + ); + } + return; + } + + if ($params.dragElm) { + e.preventDefault(); + if ($params.$window.getSelection) { + $params.$window.getSelection().removeAllRanges(); + } else if ($params.$window.document.selection) { + $params.$window.document.selection.empty(); + } + + var eventObj = $TreeDnDHelper.eventObj(e), + leftElmPos = eventObj.pageX - $params.pos.offsetX, + topElmPos = eventObj.pageY - $params.pos.offsetY; + + //dragElm can't leave the screen on the left + if (leftElmPos < 0) { + leftElmPos = 0; + } + + //dragElm can't leave the screen on the top + if (topElmPos < 0) { + topElmPos = 0; + } + + //dragElm can't leave the screen on the bottom + if (topElmPos + 10 > $params.document_height) { + topElmPos = $params.document_height - 10; + } + + //dragElm can't leave the screen on the right + if (leftElmPos + 10 > $params.document_width) { + leftElmPos = $params.document_width - 10; + } + + $params.dragElm.css( + { + 'left': leftElmPos + _$scope.$callbacks.calsIndent( + $params.offsetEdge + 1, + true, + true + ) + 'px', + 'top': topElmPos + 'px' + } + ); + + if (_$scope.enabledStatus) { + _$scope.setPositionStatus(e); + } + + var top_scroll = window.pageYOffset || $params.$window.document.documentElement.scrollTop, + bottom_scroll = top_scroll + (window.innerHeight || $params.$window.document.clientHeight || $params.$window.document.clientHeight); + // to scroll down if cursor y-position is greater than the bottom position the vertical scroll + if (bottom_scroll < eventObj.pageY && bottom_scroll <= $params.document_height) { + window.scrollBy(0, 10); + } + // to scroll top if cursor y-position is less than the top position the vertical scroll + if (top_scroll > eventObj.pageY) { + window.scrollBy(0, -10); + } + + $TreeDnDHelper.positionMoved(e, $params.pos, $params.firstMoving); + + if ($params.firstMoving) { + $params.firstMoving = false; + return; + } + // check if add it as a child node first + + var targetX = eventObj.pageX - $params.$window.document.body.scrollLeft, + targetY = eventObj.pageY - (window.pageYOffset || $params.$window.document.documentElement.scrollTop), + + targetElm, + targetScope, + targetBefore, + targetOffset, + isChanged = true, + isVeritcal = true, + isEmpty, + isSwapped, + _scope, + _target, + _parent, + _info = $params.dragInfo, + _move = _info.move, + _drag = _info.node, + _drop = _info.drop, + treeScope = _info.target, + fnSwapTree, + isHolder = _fnPlaceHolder(e, $params); + + if (!isHolder) { + /* when using elementFromPoint() inside an iframe, you have to call + elementFromPoint() twice to make sure IE8 returns the correct value + $params.$window.document.elementFromPoint(targetX, targetY);*/ + + targetElm = angular.element( + $params.$window.document.elementFromPoint( + targetX, + targetY + ) + ); + + targetScope = targetElm.scope(); + if (!targetScope || !targetScope.$callbacks || !targetScope.$callbacks.droppable()) { + // Not allowed Drop Item + return; + } + + fnSwapTree = function () { + treeScope = targetScope.getScopeTree(); + _target = _info.target; + + if (_info.target !== treeScope) { + // Replace by place-holder new + _target.hidePlace(); + _target.targeting = false; + treeScope.targeting = true; + + _info.target = treeScope; + $params.placeElm = treeScope.initPlace(targetScope.$element, $params.dragElm); + + _target = null; + isSwapped = true; + } + return true; + }; + + if (angular.isFunction(targetScope.getScopeNode)) { + targetScope = targetScope.getScopeNode(); + if (!fnSwapTree()) { + return; + } + } else { + if (targetScope.$type === 'TreeDnDNodes' || targetScope.$type === 'TreeDnD') { + if (targetScope.tree_nodes) { + if (targetScope.tree_nodes.length === 0) { + if (!fnSwapTree()) { + return; + } + // Empty + isEmpty = true; + } + } else { + return; + } + } else { + return; + } + } + } + + if ($params.pos.dirAx && !isSwapped || isHolder) { + isVeritcal = false; + targetScope = _info.scope; + } + + if (!targetScope.$element && !targetScope) { + return; + } + + if (isEmpty) { + _move.parent = null; + _move.pos = 0; + + _drop = null; + } else { + // move vertical + if (isVeritcal) { + targetElm = targetScope.$element; // Get the element of tree-dnd-node + if (angular.isUndefinedOrNull(targetElm)) { + return; + } + targetOffset = $TreeDnDHelper.offset(targetElm); + + if (targetScope.horizontal && !targetScope.isTable) { + targetBefore = eventObj.pageX < targetOffset.left + $TreeDnDHelper.width(targetElm) / 2; + } else { + if (targetScope.isTable) { + targetBefore = eventObj.pageY < targetOffset.top + $TreeDnDHelper.height(targetElm) / 2; + } else { + var _height = $TreeDnDHelper.height(targetElm); + + if (targetScope.getElementChilds()) { + _height -= -$TreeDnDHelper.height(targetScope.getElementChilds()); + } + + if (eventObj.pageY > targetOffset.top + _height) { + return; + } + + targetBefore = eventObj.pageY < targetOffset.top + _height / 2; + } + } + + if (!angular.isFunction(targetScope.getData)) { + return; + } + + _target = targetScope.getData(); + _parent = targetScope.getNode(_target.__parent_real__); + + if (targetBefore) { + var _prev = targetScope.getPrevSibling(_target); + + _move.parent = _parent; + _move.pos = angular.isDefined(_prev) ? _prev.__index__ + 1 : 0; + + _drop = _prev; + } else { + if (_target.__expanded__ && !(_target.__children__.length === 1 && _target.__index_real__ === _drag.__parent_real__)) { + _move.parent = _target; + _move.pos = 0; + + _drop = null; + } else { + _move.parent = _parent; + _move.pos = _target.__index__ + 1; + + _drop = _target; + } + } + } else { + // move horizontal + if ($params.pos.dirAx && $params.pos.distAxX >= treeScope.dragBorder) { + $params.pos.distAxX = 0; + // increase horizontal level if previous sibling exists and is not collapsed + if ($params.pos.distX > 0) { + _parent = _drop; + if (!_parent) { + if (_move.pos - 1 >= 0) { + _parent = _move.parent.__children__[_move.pos - 1]; + } else { + return; + } + } + + if (_info.drag === _info.target && _parent === _drag && _$scope.enabledMove) { + _parent = treeScope.getPrevSibling(_parent); + } + + if (_parent && _parent.__visible__) { + var _len = _parent.__children__.length; + + _move.parent = _parent; + _move.pos = _len; + + if (_len > 0) { + _drop = _parent.__children__[_len - 1]; + } else { + _drop = null; + } + } else { + // Not changed + return; + } + } else if ($params.pos.distX < 0) { + _target = _move.parent; + if (_target && + (_target.__children__.length === 0 || + _target.__children__.length - 1 < _move.pos || + _info.drag === _info.target && + _target.__index_real__ === _drag.__parent_real__ && + _target.__children__.length - 1 === _drag.__index__ && _$scope.enabledMove) + ) { + _parent = treeScope.getNode(_target.__parent_real__); + + _move.parent = _parent; + _move.pos = _target.__index__ + 1; + + _drop = _target; + } else { + // Not changed + return; + } + } else { + return; + } + } else { + // limited + return; + } + } + } + + if (_info.drag === _info.target && + _move.parent && + _drag.__parent_real__ === _move.parent.__index_real__ && + _drag.__index__ === _move.pos + ) { + isChanged = false; + } + + if (treeScope.$callbacks.accept(_info, _move, isChanged)) { + _info.move = _move; + _info.drop = _drop; + _info.changed = isChanged; + _info.scope = targetScope; + + if (targetScope.isTable) { + $TreeDnDHelper.replaceIndent( + treeScope, + $params.placeElm, + angular.isUndefinedOrNull(_move.parent) ? 1 : _move.parent.__level__ + 1 + ); + + if (_drop) { + _parent = (_move.parent ? _move.parent.__children__ : null ) || _info.target.treeData; + + if (_drop.__index__ < _parent.length - 1) { + // Find fast + _drop = _parent[_drop.__index__ + 1]; + _scope = _info.target.getScope(_drop); + _scope.$element[0].parentNode.insertBefore( + $params.placeElm[0], + _scope.$element[0] + ); + } else { + _target = _info.target.getLastDescendant(_drop); + _scope = _info.target.getScope(_target); + _scope.$element.after($params.placeElm); + } + } else { + _scope = _info.target.getScope(_move.parent); + if (_scope) { + if (_move.parent) { + _scope.$element.after($params.placeElm); + + } else { + _scope.getElementChilds().prepend($params.placeElm); + } + } + } + } else { + _scope = _info.target.getScope(_drop || _move.parent); + if (_drop) { + _scope.$element.after($params.placeElm); + } else { + _scope.getElementChilds().prepend($params.placeElm); + } + } + + treeScope.showPlace(); + + _$scope.$safeApply( + function () { + _$scope.$callbacks.dragMove(_info); + } + ); + } + + } + } + + function _fnDragEnd(e, $params) { + e.preventDefault(); + if ($params.dragElm) { + var _passed = false, + _$scope = $params.$scope, + _scope = _$scope.getScope($params.dragInfo.node), + _element = _scope.$element; + + _$scope.$safeApply( + function () { + _passed = _$scope.$callbacks.beforeDrop($params.dragInfo); + } + ); + + // rollback all + if (_scope.isTable) { + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + return _node.__visible__ === false || _node.__expanded__ === false + }, null, true + ); + } else { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + + $params.dragElm.remove(); + $params.dragElm = null; + + if (_$scope.enabledStatus) { + _$scope.hideStatus(); + } + + if (_$scope.$$apply) { + _$scope.$safeApply( + function () { + var _status = _$scope.$callbacks.dropped( + $params.dragInfo, + _passed + ); + + _$scope.$callbacks.dragStop($params.dragInfo, _status); + clearData(); + } + ); + } else { + _fnBindDrag($params); + _$scope.$safeApply( + function () { + _$scope.$callbacks.dragStop($params.dragInfo, false); + clearData(); + } + ); + } + + } + + function clearData() { + $params.dragInfo.target.hidePlace(); + $params.dragInfo.target.targeting = false; + + $params.dragInfo = null; + _$scope.$$apply = false; + _$scope.setDragging(null); + } + + angular.element($params.$document).unbind('touchend', $params.dragEndEvent); // Mobile + angular.element($params.$document).unbind('touchcancel', $params.dragEndEvent); // Mobile + angular.element($params.$document).unbind('touchmove', $params.dragMoveEvent); // Mobile + angular.element($params.$document).unbind('mouseup', $params.dragEndEvent); + angular.element($params.$document).unbind('mousemove', $params.dragMoveEvent); + angular.element($params.$window.document.body).unbind('mouseleave', $params.dragCancelEvent); + } + + function _fnDragStartEvent(e, $params) { + if ($params.$scope.$callbacks.draggable()) { + _fnDragStart(e, $params); + } + } + + function _fnBindDrag($params) { + $params.element.bind( + 'touchstart mousedown', function (e) { + $params.dragDelaying = true; + $params.dragStarted = false; + _fnDragStartEvent(e, $params); + $params.dragTimer = $timeout( + function () { + $params.dragDelaying = false; + }, $params.$scope.dragDelay + ); + } + ); + + $params.element.bind( + 'touchend touchcancel mouseup', function () { + $timeout.cancel($params.dragTimer); + } + ); + } + + function _fnKeydownHandler(e, $params) { + var _$scope = $params.$scope; + if (e.keyCode === 27) { + if (_$scope.enabledStatus) { + _$scope.hideStatus(); + } + + _$scope.$$apply = false; + _fnDragEnd(e, $params); + } else { + if (_$scope.enabledHotkey && e.shiftKey) { + _$scope.enableMove(true); + if (_$scope.enabledStatus) { + _$scope.refreshStatus(); + } + + if (!$params.dragInfo) { + return; + } + + var _scope = _$scope.getScope($params.dragInfo.node), + _element = _scope.$element; + + if (_scope.isTable) { + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) { + if (_$scope.$class.hidden) { + _element.addClass(_$scope.$class.hidden); + } + } + return _node.__visible__ === false || _node.__expanded__ === false + + }, null, true + ); + } else { + if (_$scope.$class.hidden) { + _element.addClass(_$scope.$class.hidden); + } + } + } + } + } + + function _fnKeyupHandler(e, $params) { + var _$scope = $params.$scope; + if (_$scope.enabledHotkey && !e.shiftKey) { + _$scope.enableMove(false); + + if (_$scope.enabledStatus) { + _$scope.refreshStatus(); + } + + if (!$params.dragInfo) { + return; + } + + var _scope = _$scope.getScope($params.dragInfo.node), + _element = _scope.$element; + + if (_scope.isTable) { + _$scope.for_all_descendants( + $params.dragInfo.node, function (_node, _parent) { + _scope = _$scope.getScope(_node); + _element = _scope && _scope.$element; + if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + return _node.__visible__ === false || _node.__expanded__ === false + }, null, true + ); + } else { + if (_$scope.$class.hidden) { + _element.removeClass(_$scope.$class.hidden); + } + } + } + } + + function _$init(scope, element, $window, $document) { + var $params = { + hasTouch: 'ontouchstart' in window, + firstMoving: null, + dragInfo: null, + pos: null, + placeElm: null, + dragElm: null, + dragDelaying: true, + dragStarted: false, + dragTimer: null, + body: document.body, + html: document.documentElement, + document_height: null, + document_width: null, + offsetEdge: null, + $scope: scope, + $window: $window, + $document: $document, + element: element, + bindDrag: function () { + _fnBindDrag($params); + }, + dragEnd: function (e) { + _fnDragEnd(e, $params); + }, + dragMoveEvent: function (e) { + _fnDragMove(e, $params); + }, + dragEndEvent: function (e) { + scope.$$apply = true; + _fnDragEnd(e, $params); + }, + dragCancelEvent: function (e) { + _fnDragEnd(e, $params); + } + }, + keydownHandler = function (e) { + return _fnKeydownHandler(e, $params); + }, + keyupHandler = function (e) { + return _fnKeyupHandler(e, $params); + }; + + scope.dragEnd = function (e) { + $params.dragEnd(e); + }; + + $params.bindDrag(); + + angular.element($window.document.body).bind('keydown', keydownHandler); + angular.element($window.document.body).bind('keyup', keyupHandler); + //unbind handler that retains scope + scope.$on( + '$destroy', function () { + angular.element($window.document.body).unbind('keydown', keydownHandler); + angular.element($window.document.body).unbind('keyup', keyupHandler); + if (scope.statusElm) { + scope.statusElm.remove(); + } + + if (scope.placeElm) { + scope.placeElm.remove(); + } + } + ); + } + + return _$init; + } + ] +); + +angular.module('ntt.TreeDnD') + .factory( + '$TreeDnDControl', function () { + var _target, _parent, + i, len; + + function fnSetCollapse(node) { + node.__expanded__ = false; + } + + function fnSetExpand(node) { + node.__expanded__ = true; + } + + function _$init(scope) { + var n, tree = { + selected_node: null, + for_all_descendants: scope.for_all_descendants, + select_node: function (node) { + if (!node) { + if (tree.selected_node) { + delete tree.selected_node.__selected__; + } + tree.selected_node = null; + return null; + } + + if (node !== tree.selected_node) { + if (tree.selected_node) { + delete tree.selected_node.__selected__; + } + node.__selected__ = true; + tree.selected_node = node; + tree.expand_all_parents(node); + if (angular.isFunction(tree.on_select)) { + tree.on_select(node); + } + } + return node; + }, + deselect_node: function () { + _target = null; + if (tree.selected_node) { + delete tree.selected_node.__selected__; + _target = tree.selected_node; + tree.selected_node = null; + } + return _target; + }, + get_parent: function (node) { + if (node && node.__parent_real__ !== null) { + return scope.tree_nodes[node.__parent_real__]; + } + return null; + }, + for_all_ancestors: function (child, fn) { + _parent = tree.get_parent(child); + if (_parent) { + if (fn(_parent)) { + return false; + } + + return tree.for_all_ancestors(_parent, fn); + } + return true; + }, + expand_all_parents: function (child) { + child = child || tree.selected_node; + if (typeof child === 'object') { + tree.for_all_ancestors( + child, fnSetExpand + ) + } + }, + collapse_all_parents: function (child) { + child = child || tree.selected_node; + if (typeof child === 'object') { + tree.for_all_ancestors( + child, fnSetCollapse + ) + } + }, + + reload_data: function () { + return scope.reload_data(); + }, + add_node: function (parent, new_node, index) { + if (typeof index !== 'number') { + if (parent) { + parent.__children__.push(new_node); + parent.__expanded__ = true; + } else { + scope.treeData.push(new_node); + } + } else { + if (parent) { + parent.__children__.splice(index, 0, new_node); + parent.__expanded__ = true; + } else { + scope.treeData.splice(index, 0, new_node); + } + } + return new_node; + }, + add_node_root: function (new_node) { + tree.add_node(null, new_node); + return new_node; + }, + expand_all: function () { + len = scope.treeData.length; + for (i = 0; i < len; i++) { + tree.for_all_descendants( + scope.treeData[i], fnSetExpand + ); + } + }, + collapse_all: function () { + len = scope.treeData.length; + for (i = 0; i < len; i++) { + tree.for_all_descendants( + scope.treeData[i], fnSetCollapse + ); + } + }, + remove_node: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + if (node.__parent_real__ !== null) { + _parent = tree.get_parent(node).__children__; + } else { + _parent = scope.treeData; + } + + _parent.splice(node.__index__, 1); + + tree.reload_data(); + + if (tree.selected_node === node) { + tree.selected_node = null; + } + } + }, + expand_node: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object' && node.__expanded__) { + node.__expanded__ = true; + return node; + } + }, + collapse_node: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + node.__expanded__ = false; + return node; + } + }, + get_selected_node: function () { + return tree.selected_node; + }, + get_first_node: function () { + len = scope.treeData.length; + if (len > 0) { + return scope.treeData[0]; + } + return null; + }, + get_children: function (node) { + return node.__children__; + }, + get_siblings: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + _parent = tree.get_parent(node); + if (_parent) { + _target = _parent.__children__; + } else { + _target = scope.treeData; + } + return _target; + } + }, + get_next_sibling: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + _target = tree.get_siblings(node); + n = _target.length; + if (node.__index__ < n) { + return _target[node.__index__ + 1]; + } + } + }, + get_prev_sibling: function (node) { + node = node || tree.selected_node; + _target = tree.get_siblings(node); + if (node.__index__ > 0) { + return _target[node.__index__ - 1]; + } + }, + get_first_child: function (node) { + node = node || tree.selected_node; + if (typeof node === 'object') { + _target = node.__children__; + if (_target && _target.length > 0) { + return node.__children__[0]; + } + } + return null; + }, + get_closest_ancestor_next_sibling: function (node) { + node = node || tree.selected_node; + _target = tree.get_next_sibling(node); + if (_target) { + return _target; + } + + _parent = tree.get_parent(node); + return tree.get_closest_ancestor_next_sibling(_parent); + }, + get_next_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_first_child(node); + if (_target) { + return _target; + } else { + return tree.get_closest_ancestor_next_sibling(node); + } + } + }, + get_prev_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_prev_sibling(node); + if (_target) { + return tree.get_last_descendant(_target); + } + + _parent = tree.get_parent(node); + return _parent; + } + }, + get_last_descendant: scope.getLastDescendant, + select_parent_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _parent = tree.get_parent(node); + if (_parent) { + return tree.select_node(_parent); + } + } + }, + select_first_node: function () { + var firstNode = tree.get_first_node(); + return tree.select_node(firstNode); + }, + select_next_sibling: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_next_sibling(node); + if (_target) { + return tree.select_node(_target); + } + } + }, + select_prev_sibling: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_prev_sibling(node); + if (_target) { + return tree.select_node(_target); + } + } + }, + select_next_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_next_node(node); + if (_target) { + return tree.select_node(_target); + } + } + }, + select_prev_node: function (node) { + node = node || tree.selected_node; + + if (typeof node === 'object') { + _target = tree.get_prev_node(node); + if (_target) { + return tree.select_node(_target); + } + } + } + }; + angular.extend(scope.tree, tree); + return scope.tree; + } + + return _$init; + } +); + +angular.module('template/TreeDnD/TreeDnD.html', []).run( + [ + '$templateCache', function ($templateCache) { + $templateCache.put( + 'template/TreeDnD/TreeDnD.html', + ['', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '
', + ' {{expandingProperty.displayName || expandingProperty.field || expandingProperty}}', + ' <\/th>', + ' ', + ' {{col.displayName || col.field}}', + '
', + ' ', + ' ', + ' ', + ' {{node[expandingProperty.field] || node[expandingProperty]}}', + ' ', + ' {{node[col.field]}}', + '
'].join('\n') + ); + + $templateCache.put( + 'template/TreeDnD/TreeDnDStatusCopy.html', + '' + ); + + $templateCache.put( + 'template/TreeDnD/TreeDnDStatusMove.html', + '' + ); + }] +); + + function isUndefinedOrNull(val) { + return angular.isUndefined(val) || val === null; + } + + function isDefined(val) { + return !(angular.isUndefined(val) || val === null); + } +})(); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.css b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.css new file mode 100644 index 0000000..9e5f832 --- /dev/null +++ b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.css @@ -0,0 +1 @@ +.tree-dnd-animate-enter,.tree-dnd-node.ng-enter{-webkit-transition:0 linear all;-moz-transition:0 linear all;-ms-transition:0 linear all;-o-transition:0 linear all;transition:0 linear all;position:relative;display:block;opacity:0;max-height:0}.tree-dnd-animate-enter.tree-dnd-animate-enter-active,.tree-dnd-node.ng-enter-active{opacity:1;max-height:30px}.tree-dnd-animate-leave,.tree-dnd-node.ng-leave{-webkit-transition:0 linear all;-moz-transition:0 linear all;-ms-transition:0 linear all;-o-transition:0 linear all;transition:0 linear all;position:relative;display:block;height:30px;max-height:30px;opacity:1}.tree-dnd-animate-leave.tree-dnd-animate-leave-active,.tree-dnd-node.ng-leave-active{height:0;max-height:0;opacity:0}.tree-dnd-node>td{position:relative}.tree-dnd .tree-icon,.tree-label{cursor:pointer}.tree-dnd>tbody>tr>td,.tree-dnd>tfoot>tr>td,.tree-dnd>thead>tr>td{vertical-align:middle!important}.tree-dnd-empty{border:2px dashed #72da67!important;min-height:100px;background-color:#e5e5e5}.tree-dnd-handle,.tree-dnd-node,.tree-dnd-placeholder{min-height:20px;line-height:20px}.indented{position:relative}.tree-dnd-hidden{-webkit-animation:fadeOut 0s;-moz-animation:fadeOut 0s;-o-animation:fadeOut 0s;animation:fadeOut 0s;display:none!important}.tree-dnd-placeholder{position:relative;margin:0;padding:0}.tree-dnd-handle{cursor:pointer;text-decoration:none;font-weight:700;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.tree-dnd-drag{position:absolute;pointer-events:none;z-index:999;opacity:.7;background-color:#cdffdc;border:2px dashed #385736}.tree-dnd-status{position:absolute;background-color:#fff;border:1px solid #92e5d3;padding:1px 4px;opacity:.85}.tree-dnd-nodes{margin:0;padding:0;list-style:none}.tree-dnd-nodes .tree-dnd-node{border-radius:0!important}.tree-dnd-nodes .tree-dnd-nodes{padding-left:20px} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.js b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.js new file mode 100644 index 0000000..7d76240 --- /dev/null +++ b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.js @@ -0,0 +1,31 @@ +/** + * The MIT License (MIT) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +/** + * Implementing TreeDnD & Event DrapnDrop (allow drag multi tree-table include all type: table, ol, ul) + * Demo: http://thienhung1989.github.io/angular-tree-dnd + * Github: https://github.com/thienhung1989/angular-tree-dnd + * @version 3.0.5 + * (c) 2015 Nguyuễn Thiện Hùng - + */ +!function(){"use strict";function e(e,n,t,a,l,r,i,d,o,s,_,c){function u(n,t,a){function c(){n.treeData=U,$(),H=null}function u(e,n,t){return angular.isUndefinedOrNull(n)?!1:"*"!==n&&angular.isUndefined(e[n])?angular.isArray(n)?g(e,n,t):void 0:!0}function g(e,n,t){var a,l=n.length,r=!1;if(0===l)return null;for(a=0;l>a;a++)if(u(e,n[a],!t)){if(r=!0,!t)return!0}else if(t)return!1;return r}function f(e,t,l,r,i,d,o){if(r=r||t,"string"==typeof e||angular.isArray(e)){if(angular.isFunction(o)&&o())return;"string"==typeof a[t]?n.$watch(a[t],function(t){"string"==typeof e&&typeof t===e||angular.isArray(e)&&e.indexOf(typeof t)>-1?n[r]=t:angular.isFunction(l)?n[r]=l(t):n[r]=l,angular.isFunction(d)&&d(n[r],n)},!0):angular.isFunction(i)?n[r]=i():angular.isUndefined(i)||(n[r]=i)}}function p(e){var n=this.$root.$$phase;"$apply"===n||"$digest"===n?e&&"function"==typeof e&&e():this.$apply(e)}function m(){if(n.treeData&&n.treeData.length){var e,t,a=n.treeData[0],l=Object.keys(a),r=new RegExp("^__([a-zA-Z0-9_-]*)__$");for(t=0,e=l.length;e>t;t++)if("string"==typeof a[l[t]]&&!r.test(l[t]))return void(n.expandingProperty=l[t]);angular.isUndefinedOrNull(n.expandingProperty)&&(n.expandingProperty=l[0])}}function h(){if(n.treeData.length){var e,t,a=[],l=n.treeData[0],r=new RegExp("(^__([a-zA-Z0-9_-]*)__$|^"+n.expandingProperty+"$)"),i=Object.keys(l);for(e=0,t=i.length;t>e;e++)"string"!=typeof l[i[e]]||r.test(i[e])||a.push({field:i[e]});n.colDefinitions=a}}function b(e,t,a,l,r,i,d){if("object"!=typeof t)return 0;var o,s,_,c,u,g;if(angular.isArray(t.__children__)||(t.__children__=[]),t.__parent_real__=l,t.__parent__=a,s=t.__children__.length,angular.isUndefinedOrNull(t.__expanded__)&&s>0&&(t.__expanded__=r0)for(o=0;s>o;o++)u+=b(e,t.__children__[o],t[n.primary_key],c,r+1,i&&t.__expanded__,o);return t.__dept__=u,u}function v(e){return angular.isDefined(n.tree_nodes)&&delete n.tree_nodes,n.tree_nodes=e,e}function $(e){var t,l,r=[];if(angular.isDefined(e)){if(!angular.isArray(e)||0===e.length)return v([]);t=e}else{if(!angular.isArray(n.treeData)||0===n.treeData.length)return v([]);t=n.treeData}if(a.expandOn||m(),a.columnDefs||h(),angular.isDefined(n.orderBy)&&(angular.isFunction(w)||(w=_("$TreeDnDOrderBy")),angular.isFunction(w)&&(t=w(t,n.orderBy))),angular.isDefined(n.filter)&&(angular.isFunction(T)||(T=_("$TreeDnDFilter")),angular.isFunction(T)&&(t=T(t,n.filter,n.filterOptions))),l=t.length,l>0){var i,d=0;for(i=0;l>i;i++)d+=b(r,t[i],null,null,1,!0,i)}return v(r),r}n.indent=20,n.indent_plus=15,n.indent_unit="px",n.$tree_class="table",n.primary_key="__uid__",n.$type="TreeDnD",n.colDefinitions=[],n.$globals={},n.$class={},n.treeData=[],n.tree_nodes=[],n.$class=angular.copy(o),angular.extend(n.$class.icon,{1:a.iconExpand||"glyphicon glyphicon-minus",0:a.iconCollapse||"glyphicon glyphicon-plus","-1":a.iconLeaf||"glyphicon glyphicon-file"}),n.for_all_descendants=function(e,t,a,l){if(angular.isFunction(t)){var r,i,d;if(t(e,a))return!1;for(d=e.__children__,i=d?d.length:0,r=0;i>r;r++)if(!n.for_all_descendants(d[r],t,e)&&!l)return!1}return!0},n.getLastDescendant=function(e){var t,a;return e||(e=n.tree?n.tree.selected_node:!1),e===!1?!1:(a=e.__children__.length,0===a?e:(t=e.__children__[a-1],n.getLastDescendant(t)))},n.getElementChilds=function(){return angular.element(t[0].querySelector("[tree-dnd-nodes]"))},n.onClick=function(e){angular.isDefined(n.tree)&&angular.isFunction(n.tree.on_click)&&setTimeout(function(){n.tree.on_click(e)},0)},n.onSelect=function(e){angular.isDefined(n.tree)&&(e!==n.tree.selected_node&&n.tree.select_node(e),angular.isFunction(n.tree.on_select)&&setTimeout(function(){n.tree.on_select(e)},0))};var y,D;n.toggleExpand=function(e,t){y=!0,angular.isFunction(t)&&!t(e)?y=!1:angular.isFunction(n.$callbacks.expand)&&!n.$callbacks.expand(e)&&(y=!1),y&&e.__children__.length>0&&(e.__expanded__=!e.__expanded__)};var x=function(e){return"#"+e.__parent__+"#"+e[n.primary_key]},E=function(e){var n=x(e);return(angular.isUndefinedOrNull(e.__hashKey__)||e.__hashKey__!==n)&&(e.__hashKey__=n),e};n.getHash=x,n.$callbacks={getHash:x,setHash:E,for_all_descendants:n.for_all_descendants,accept:function(e,t,a){return n.dropEnabled===!0},calsIndent:function(e,t,a){var l=0,r=a?0:n.indent_plus;return t||(l=n.indent_unit?n.indent_unit:"px"),1>e-1?r+l:n.indent*(e-1)+r+l},droppable:function(){return n.dropEnabled===!0},draggable:function(){return n.dragEnabled===!0},beforeDrop:function(e){return!0},changeKey:function(e){var t=e.__uid__;e.__uid__=Math.random(),e.__selected__&&delete e.__selected__,"__uid__"!==n.primary_key&&(t=""+e[n.primary_key],t=t.replace(/_#.+$/g,"")+"_#"+e.__uid__,e[n.primary_key]=t)},clone:function(e,n){return D=angular.copy(e),this.for_all_descendants(D,this.changeKey),D},remove:function(e,t,a,l){var r=t.splice(e.__index__,1)[0];return l||n.reload_data(),r},clearInfo:function(e){delete e.__inited__,delete e.__visible__},add:function(e,n,t,a){this.for_all_descendants(e,this.clearInfo),t&&(t.length>-1&&n>-1?t.splice(n,0,e):t.push(e))}},n.deleteScope=function(e,t){var a=t.__hashKey__;n.$globals[a]&&n.$globals[a]===e&&delete n.$globals[a]},n.setScope=function(e,t){var a=t.__hashKey__;n.$globals[a]!==e&&(n.$globals[a]=e)},n.getScope=function(e){if(e){var t=e.__hashKey__;return n.$globals[t]}return n},(a.enableDrag||a.enableDrop)&&(n.placeElm=null,n.dragEnabled=null,n.dropEnabled=null,n.horizontal=null,a.enableDrag&&(n.dragDelay=0,n.enabledMove=!0,n.statusMove=!0,n.enabledHotkey=!1,n.enabledCollapse=null,n.statusElm=null,n.dragging=null,angular.extend(n.$callbacks,{beforeDrag:function(e){return!0},dragStop:function(e,n){return!e||!e.changed&&e.drag.enabledMove||!n?null:(e.target.reload_data(),void(e.target!==e.drag&&e.drag.enabledMove&&e.drag.reload_data()))},dropped:function(e,n){if(!e)return null;var t=e.node,a=null,l=e.move,r=null,i=e.parent||e.drag.treeData,d=l.parent||e.target.treeData,o=e.drag.enabledMove;return!e.changed&&o?!1:e.target.$callbacks.accept(e,e.move,e.changed)?(o?(r=i,angular.isDefined(r.__children__)&&(r=r.__children__),a=e.drag.$callbacks.remove(t,r,e.drag.$callbacks,!0)):a=e.drag.$callbacks.clone(t,e.drag.$callbacks),o&&e.drag===e.target&&i===d&&l.pos>=e.node.__index__&&l.pos--,r=d,r.__children__&&(r=r.__children__),e.target.$callbacks.add(a,l.pos,r,e.drag.$callbacks),!0):!1},dragStart:function(e){},dragMove:function(e){}}),n.setDragging=function(e){n.dragging=e},n.enableMove=function(e){"boolean"==typeof e?n.enabledMove=e:n.enabledMove=!0},a.enableStatus&&(n.enabledStatus=!1,n.hideStatus=function(){n.statusElm&&n.statusElm.addClass(n.$class.hidden)},n.refreshStatus=function(){if(n.dragging&&n.enabledStatus){var e=n.statusElm;n.enabledMove?n.statusElm=angular.element(d.getMove(n)):n.statusElm=angular.element(d.getCopy(n)),e!==n.statusElm&&(e&&(n.statusElm.attr("class",e.attr("class")),n.statusElm.attr("style",e.attr("style")),e.remove()),r.find("body").append(n.statusElm)),n.statusElm.removeClass(n.$class.hidden)}},n.setPositionStatus=function(e){n.statusElm&&(n.statusElm.css({left:e.pageX+10+"px",top:e.pageY+15+"px","z-index":9999}),n.statusElm.addClass(n.$class.status))})),n.targeting=!1,n.getPrevSibling=function(e){if(e&&e.__index__>0){var t,a=e.__index__-1;return angular.isDefined(e.__parent_real__)?(t=n.tree_nodes[e.__parent_real__],t.__children__[a]):n.treeData[a]}return null},n.getNode=function(e){return angular.isUndefinedOrNull(e)?null:n.tree_nodes[e]},n.initPlace=function(e,t){if(!n.placeElm)if(n.isTable){n.placeElm=angular.element(l.document.createElement("tr"));var a=n.colDefinitions.length;for(n.placeElm.append(angular.element(l.document.createElement("td")).addClass(n.$class.empty).addClass("indented").addClass(n.$class.place));a-- >0;)n.placeElm.append(angular.element(l.document.createElement("td")).addClass(n.$class.empty).addClass(n.$class.place))}else n.placeElm=angular.element(l.document.createElement("li")).addClass(n.$class.empty).addClass(n.$class.place);return t&&n.placeElm.css("height",s.height(t)+"px"),e?e[0].parentNode.insertBefore(n.placeElm[0],e[0]):n.getElementChilds().append(n.placeElm),n.placeElm},n.hidePlace=function(){n.placeElm&&n.placeElm.addClass(n.$class.hidden)},n.showPlace=function(){n.placeElm&&n.placeElm.removeClass(n.$class.hidden)},n.getScopeTree=function(){return n}),n.$safeApply=p,n.hiddenChild=function(e,t){var a=n.getScope(e);return a?t&&t.__expanded__&&t.__visible__?(a.$element.removeClass(n.$class.hidden),e.__visible__=!0):(a.$element.addClass(n.$class.hidden),e.__visible__=!1):t&&t.__expanded__&&t.__visible__?e.__visible__=!0:e.__visible__=!1,e.__expanded__===!1};var T,w,C,S,k,M,A,P,Y,j,O,X,I,N,F,H,U,K={showParent:!0,showChild:!1,beginAnd:!0},L=[["enableDrag",[["boolean","enableStatus",null,"enabledStatus"],["boolean","enableMove",null,"enabledMove"],["number","dragDelay",0,null,0],["boolean","enableCollapse",null,"enabledCollapse"],["boolean","enableHotkey",null,"enabledHotkey",null,function(e){e?n.enabledMove=!1:n.enabledMove=n.statusMove}]]],[["enableDrag","enableStatus"],[["string","templateCopy",a.templateCopy,"templateCopy",null,function(e){e&&i.get(e)&&d.setCopy(e,n)}],["string","templateMove",a.templateMove,"templateMove",null,function(e){e&&i.get(e)&&d.setMove(e,n)}]]],[[["enableDrag","enableDrop"]],[["number","dragBorder",30,"dragBorder",30]]],["*",[["boolean","treeTable",!0,"treeTable",null],["boolean","horizontal"],["callback","treeClass",function(e){switch(typeof e){case"string":n.$tree_class=e;break;case"object":angular.extend(n.$class,e),n.$tree_class=n.$class.tree;break;default:n.$tree_class=a.treeClass}},"treeClass",function(){n.$tree_class=n.$class.tree+" table"},null,function(){return/^(\s+[\w\-]+){2,}$/g.test(" "+a.treeClass)?(n.$tree_class=a.treeClass.trim(),!0):void 0}],[["object","string"],"expandOn",m,"expandingProperty",m,function(e){angular.isUndefinedOrNull(e)&&(n.expandingProperty=a.expandOn)}],["object","treeControl",angular.isDefined(n.tree)?n.tree:{},"tree",null,function(e){angular.isFunction(C)||(C=_("$TreeDnDControl")),angular.isFunction(C)&&(S=angular.extend(e,C(n)))}],[["array","object"],"columnDefs",h,"colDefinitions",h,function(e){!angular.isUndefinedOrNull(e)&&angular.isArray(e)||(n.colDefinitions=h())}],[["object","string","array","function"],"orderBy",a.orderBy],[["object","array"],"filter",null,"filter",null,function(e){var t=!1;if(angular.isDefined(e)&&!angular.isArray(e)){var a,l=Object.keys(e),r=l.length;if(r>0)for(a=0;r>a;a++)if("string"!=typeof e[l[a]]||0!==e[l[a]].length){t=!0;break}}n.enabledFilter=t,$()}],["object","filterOptions",K,"filterOptions",K,function(e){"object"==typeof e&&(n.filterOptions=angular.extend(K,e))}],["string","primaryKey",a.primaryKey,"primary_key","__uid__"],["string","indentUnit",a.indentUnit,"indent_unit"],["number","indent",30,null,30],["number","indentPlus",20,null,20],["null","callbacks",function(e){return angular.forEach(e,function(e,t){"function"==typeof e&&n.$callbacks[t]&&(n.$callbacks[t]=e)}),n.$callbacks},"$callbacks"],["number","expandLevel",3,"expandLevel",3,function(){$()}],["number","treeLimit",100,"$TreeLimit",100],["boolean","enableDrag",null,"dragEnabled"],["boolean","enableDrop",null,"dropEnabled"]]]],B=L.length;for(k=0;B>k;k++)if(u(a,L[k][0],!0))for(P=L[k][1],M=0,A=P.length;A>M;M++)Y=P[M][0],j=P[M][1],O=P[M][2],X=P[M][3],I=P[M][4],N=P[M][5],F=P[M][6],f(Y,j,O,X,I,N,F);a.treeData&&n.$watch(a.treeData,function(t){angular.equals(t,n.treeData)||(U=t,angular.isUndefinedOrNull(H)&&(H=e(c,350)))},!0),n.updateLimit=function(){n.$TreeLimit+=50},n.reload_data=$}function g(e){var o="",s=e.html().trim();return s.length>0&&(o=s,e.html("")),function(e,s,u){if(u.enableDrag){var g=_("$TreeDnDDrag");angular.isFunction(g)&&g(e,s,l,r)}s.ready(function(){function l(e,t){var l,r=e[0].querySelector("[tree-dnd-node]");if(t.isTable=null,r){if(r=angular.element(r),l=r.attr("ng-include")){var d=a(l)(t)||l;if("string"==typeof d)return n.get(d,{cache:i}).success(function(e){e=e.trim();var n=document.createElement("div");n.innerHTML=e,n=angular.element(n),t.isTable=!n[0].querySelector("[tree-dnd-nodes]")})}else t.isTable=!r[0].querySelector("[tree-dnd-nodes]");c.setTemplate(t,t.templateNode)}}var r;o.length>0?(r=l(angular.element(o.trim()),e),"object"==typeof r?r.then(function(){s.append(t(o)(e))}):s.append(t(o)(e))):n.get(u.templateUrl||d.getPath(),{cache:i}).success(function(n){n=angular.element(n.trim()),r=l(n,e),"object"==typeof r?r.then(function(){s.append(t(n)(e))}):s.append(t(n)(e))})})}}return{restrict:"E",scope:!0,replace:!0,controller:["$scope","$element","$attrs",u],compile:g}}function n(e,n,t,a,l){function r(){return g={width:x.prop("offsetWidth")||document.documentElement.clientWidth,height:x.prop("offsetHeight")||document.documentElement.clientHeight,top:n[0].body.scrollTop||n[0].documentElement.scrollTop,left:n[0].body.scrollLeft||n[0].documentElement.scrollLeft},b||v?void($=!0):(b=!0,void i())}function i(){if(!v){var e,n=n>0?n:y.length;n>0?(e=y[0],v=!0,m=t(function(){y.splice(0,1),v=!1,n--,t.cancel(m),i()},0)):(b=!1,$&&($=!1,r()))}}function d(e){h=e}function o(){return h}function s(){t.cancel(p),p=t(function(){r()},0)}function _(e,n){s(),y.push({element:n,scope:e})}function c(e,n){f=n}function u(){return y}var g,f,p,m,h=null,b=!1,v=!1,$=!1,y=[],D={setViewport:d,getViewport:o,add:_,setTemplate:c,getItems:u,updateDelayed:s},x=angular.element(e);return x.on("load resize scroll",s),D}function t(e){return angular.isUndefined(e)||null===e}function a(e){return!(angular.isUndefined(e)||null===e)}angular.isUndefinedOrNull=t,angular.isDefined=a,angular.module("ntt.TreeDnD",["template/TreeDnD/TreeDnD.html"]).constant("$TreeDnDClass",{tree:"tree-dnd",empty:"tree-dnd-empty",hidden:"tree-dnd-hidden",node:"tree-dnd-node",nodes:"tree-dnd-nodes",handle:"tree-dnd-handle",place:"tree-dnd-placeholder",drag:"tree-dnd-drag",status:"tree-dnd-status",icon:{1:"glyphicon glyphicon-minus",0:"glyphicon glyphicon-plus","-1":"glyphicon glyphicon-file"}}),angular.module("ntt.TreeDnD").directive("compile",["$compile",function(e){return{restrict:"A",link:function(n,t,a){n.$watch(a.compile,function(a){a&&(angular.isFunction(t.empty)?t.empty():t.html(""),t.append(e(a)(n)))})}}}]).directive("compileReplace",["$compile",function(e){return{restrict:"A",link:function(n,t,a){n.$watch(a.compileReplace,function(a){a&&t.replaceWith(e(a)(n))})}}}]),angular.module("ntt.TreeDnD").directive("treeDndNodeHandle",function(){return{restrict:"A",scope:!0,link:function(e,n,t){e.$type="TreeDnDNodeHandle",e.$class.handle&&n.addClass(e.$class.handle)}}}),angular.module("ntt.TreeDnD").directive("treeDndNode",["$TreeDnDViewport","$timeout",function(e,n){function t(n,t,a){function l(e,n,a){var l,i=a[d];if(o)l=i.__icon__,i.__icon_class__=a.$class.icon[l];else{var s,_=i.__parent_real__,c=a.tree_nodes[_]||null,u=i.__children__,g=u.length;if(i.__inited__||(i.__inited__=!0),i.__hashKey__!==f&&(a.deleteScope(a,i),a.setScope(a,i),f=i.__hashKey__),!c||c.__expanded__&&c.__visible__?(t.removeClass(a.$class.hidden),i.__visible__=!0):(t.addClass(a.$class.hidden),i.__visible__=!1),l=0===g?-1:i.__expanded__?1:0,i.__icon__=l,i.__icon_class__=a.$class.icon[l],a.isTable)for(s=0;g>s;s++)a.for_all_descendants(u[s],a.hiddenChild,i,!0);else r||(r=a.getElementChilds()),i.__expanded__?r.removeClass(a.$class.hidden):r.addClass(a.$class.hidden)}o=!1}n.$node_class="",n.$class.node&&(t.addClass(n.$class.node),n.$node_class=n.$class.node);var r,i="boolean"==typeof n.dragEnabled||"boolean"==typeof n.dropEnabled,d=a.treeDndNode,o=!0;e.add(n,t),i&&(n.$type="TreeDnDNode",n.getData=function(){return n[d]}),n.$element=t,n[d].__inited__=!0,n.getElementChilds=function(){return angular.element(t[0].querySelector("[tree-dnd-nodes]"))},n.setScope(n,n[d]),n.getScopeNode=function(){return n};var s,_,c=[],u=Object.keys(n[d]),g=u.length,f=n[d].__hashKey__,p=["__visible__","__children__","__level__","__index__","__index_real__","__parent__","__parent_real__","__dept__","__icon__","__icon_class__"],m=["__expanded__"],h=m.length;for(_=0;g+h>_;_++)g>_?-1===p.indexOf(u[_])&&c.push(d+"."+u[_]):-1===u.indexOf(m[_-g])&&c.push(d+"."+m[_-g]);s="["+c.join(",")+"]",n.$watch(s,l,!0),n.$on("$destroy",function(){n.deleteScope(n,n[d])})}return{restrict:"A",replace:!0,link:t}}]),angular.module("ntt.TreeDnD").directive("treeDndNodes",function(){return{restrict:"A",replace:!0,link:function(e,n){e.$type="TreeDnDNodes",e.$class.nodes?(n.addClass(e.$class.nodes),e.$nodes_class=e.$class.nodes):e.$nodes_class=""}}}),angular.module("ntt.TreeDnD").directive("treeDnd",e),e.$inject=["$timeout","$http","$compile","$parse","$window","$document","$templateCache","$TreeDnDTemplate","$TreeDnDClass","$TreeDnDHelper","$TreeDnDPlugin","$TreeDnDViewport"],angular.module("ntt.TreeDnD").factory("$TreeDnDFilter",["$filter",function(e){function n(e,t,a,l,r,i){if(!angular.isFunction(l))return null;var d,o,s,_=l(e,t),c=!1,u=e.filter_index;if(angular.isDefined(t[a])){for(s=t[a],o=s.length,e.filter_index=0,d=0;o>d;d++)c=n(e,s[d],a,l,r,_||i)||c;e.filter_index=u}return angular.isFunction(r)&&r(e,t,_===!0,c===!0,i===!0),_||c}function t(n,t){if(angular.isUndefinedOrNull(t)||angular.isArray(t))return null;if(angular.isFunction(n))return n(t,e);if("boolean"==typeof n)return t=!!t,t===n;if(!angular.isDefined(n))return null;try{var a=new RegExp(n);return a.test(t)}catch(l){return"string"==typeof t?t.indexOf(n)>-1:null}}function a(e,n,a){if(angular.isArray(n))return l(e,n,a);var r,i,d,o=n.field,s=n.callback;if("_$"===o){for(i=Object.keys(e),d=i.length,r=0;d>r;r++)if(t(s,e[i[r]]))return!0}else if(angular.isDefined(e[o]))return t(s,e[o]);return null}function l(e,n,t){var l,r=n.length||0,i=!1;if(0===r)return null;for(l=0;r>l;l++)if(a(e,n[l],!t)){if(i=!0,!t)return!0}else if(t)return!1;return i}function r(e,n,t,a,l){return t===!0?(n.__filtered__=!0,n.__filtered_visible__=!0,void(n.__filtered_index__=e.filter_index++)):a===!0&&e.showParent===!0||l===!0&&e.showChild===!0?(n.__filtered__=!1,n.__filtered_visible__=!0,void(n.__filtered_index__=e.filter_index++)):(delete n.__filtered__,delete n.__filtered_visible__,void delete n.__filtered_index__)}function i(e,n){return 0===e.filter.length?!0:a(n,e.filter,e.beginAnd||!1)}function d(e,n){return!1}function o(e){var n,t,a,l,r;if(angular.isObject(e)&&!angular.isArray(e)){if(a=Object.keys(e),t=a.length,l=[],t>0)for(n=0;t>n;n++)"string"==typeof e[a[n]]&&0===e[a[n]].length||(r=angular.isArray(e[a[n]])?e[a[n]]:angular.isObject(e[a[n]])?o(e[a[n]]):{field:a[n],callback:e[a[n]]},l.push(r));return r=null,l}return e}function s(e,t,a,l){if(!angular.isArray(e)||0===e.length)return e;var s,_,c;if(c=o(t),!angular.isArray(c)&&!angular.isObject(c)||0===c.length){for(s=0,_=e.length;_>s;s++)n(a,e[s],l||"__children__",d,r);return e}for(a.filter=c,a.filter_index=0,s=0,_=e.length;_>s;s++)n(a,e[s],l||"__children__",i,r);return e}return s}]),angular.module("ntt.TreeDnD").factory("$TreeDnDOrderBy",["$filter",function(e){var n=e("orderBy"),t=function r(e,n,t,a){var l,i,d;if(angular.isDefined(n[t])){for(d=n[t],i=d.length,l=0;i>l;l++)d[l]=r(e,d[l],t,a);n[t]=a(n[t],e)}return n},a=function(e,t){return n(e,t)},l=function(e,n){if(!angular.isArray(e)||0===e.length||!(angular.isArray(n)||angular.isObject(n)||angular.isString(n)||angular.isFunction(n))||0===n.length&&!angular.isFunction(n))return e;var l,r;for(l=0,r=e.length;r>l;l++)e[l]=t(n,e[l],"__children__",a);return a(e,n)};return l}]),angular.module("ntt.TreeDnD").factory("$TreeDnDConvert",function(){var e={line2tree:function(e,n,t,a){if(a="function"==typeof a?a:function(){},!e||0===e.length||!n||!t)return[];for(var l,r,i=[],d=[],o=e[0],s=o[n],_={},c=e.length,u=0;c>u;)o=e[u++],a(o),s=o[n],_[s]=o;for(u=0;c>u;)o=e[u++],a(o),s=o[n],_[s]=o,l=o[t],l?(r=_[l],r&&(r.__children__?r.__children__.push(o):r.__children__=[o])):d.push(s);for(c=d.length,u=0;c>u;u++)i.push(_[d[u]]);return i},tree2tree:function n(e,t,a){a="function"==typeof a?a:function(){};var l,r,i,d=[],o=e?e.length:0;for(l=0;o>l;l++)r=angular.copy(e[l]),a(r),angular.isArray(r[t])&&r[t].length>0&&(i=n(r[t],t,a),delete r[t],r.__children__=i),d.push(r);return d}};return e}),angular.module("ntt.TreeDnD").factory("$TreeDnDHelper",["$document","$window",function(e,n){var t={nodrag:function(e){return"undefined"!=typeof e.attr("data-nodrag")},eventObj:function(e){var n=e;return void 0!==e.targetTouches?n=e.targetTouches.item(0):void 0!==e.originalEvent&&void 0!==e.originalEvent.targetTouches&&(n=e.originalEvent.targetTouches.item(0)),n},dragInfo:function(e){var n=e.getData(),t=e.getScopeTree(),a=e.getNode(n.__parent_real__);return{node:n,parent:a,move:{parent:a,pos:n.__index__},scope:e,target:t,drag:t,drop:e.getPrevSibling(n),changed:!1}},height:function(e){return e.prop("scrollHeight")},width:function(e){return e.prop("scrollWidth")},offset:function(t){var a=t[0].getBoundingClientRect();return{width:t.prop("offsetWidth"),height:t.prop("offsetHeight"),top:a.top+(n.pageYOffset||e[0].body.scrollTop||e[0].documentElement.scrollTop),left:a.left+(n.pageXOffset||e[0].body.scrollLeft||e[0].documentElement.scrollLeft)}},positionStarted:function(e,n){var t={};return t.offsetX=e.pageX-this.offset(n).left,t.offsetY=e.pageY-this.offset(n).top,t.startX=t.lastX=e.pageX,t.startY=t.lastY=e.pageY,t.nowX=t.nowY=t.distX=t.distY=t.dirAx=0,t.dirX=t.dirY=t.lastDirX=t.lastDirY=t.distAxX=t.distAxY=0,t},positionMoved:function(e,n,t){n.lastX=n.nowX,n.lastY=n.nowY,n.nowX=e.pageX,n.nowY=e.pageY,n.distX=n.nowX-n.lastX,n.distY=n.nowY-n.lastY,n.lastDirX=n.dirX,n.lastDirY=n.dirY,n.dirX=0===n.distX?0:n.distX>0?1:-1,n.dirY=0===n.distY?0:n.distY>0?1:-1;var a=Math.abs(n.distX)>Math.abs(n.distY)?1:0;return t?(n.dirAx=a,void(n.moving=!0)):(n.dirAx!==a?(n.distAxX=0,n.distAxY=0):(n.distAxX+=Math.abs(n.distX),0!==n.dirX&&n.dirX!==n.lastDirX&&(n.distAxX=0),n.distAxY+=Math.abs(n.distY),0!==n.dirY&&n.dirY!==n.lastDirY&&(n.distAxY=0)),void(n.dirAx=a))},replaceIndent:function(e,n,t,a){a=a||"left",angular.element(n.children()[0]).css(a,e.$callbacks.calsIndent(t))}};return t}]),angular.module("ntt.TreeDnD").factory("$TreeDnDPlugin",["$injector",function(e){var n=function(n){return angular.isDefined(e)&&e.has(n)?e.get(n):null};return n}]),angular.module("ntt.TreeDnD").factory("$TreeDnDTemplate",["$templateCache",function(e){var n,t="template/TreeDnD/TreeDnD.html",a="template/TreeDnD/TreeDnDStatusCopy.html",l="template/TreeDnD/TreeDnDStatusMove.html",r={},i={setMove:function(e,n){r[n.$id]||(r[n.$id]={}),r[n.$id].movePath=e},setCopy:function(e,n){r[n.$id]||(r[n.$id]={}),r[n.$id].copyPath=e},getPath:function(){return t},getCopy:function(t){return r[t.$id]&&r[t.$id].copyPath&&(n=e.get(r[t.$id].copyPath))?n:e.get(a)},getMove:function(t){return r[t.$id]&&r[t.$id].movePath&&(n=e.get(r[t.$id].movePath))?n:e.get(l)}};return i}]),angular.module("ntt.TreeDnD").factory("$TreeDnDViewport",n),n.$inject=["$window","$document","$timeout","$q","$compile"],angular.module("ntt.TreeDnD").factory("$TreeDnDDrag",["$timeout","$TreeDnDHelper",function(e,n){function t(e,t){if(t.placeElm){var a=n.offset(t.placeElm);if(a.top<=e.pageY&&e.pageY<=a.top+a.height&&a.left<=e.pageX&&e.pageX<=a.left+a.width)return!0}return!1}function a(e,t){if((t.hasTouch||2!==e.button&&3!==e.which)&&!(e.uiTreeDragging||e.originalEvent&&e.originalEvent.uiTreeDragging)){var a=angular.element(e.target),l=a.scope();if(l&&l.$type&&"TreeDnDNodeHandle"===l.$type){var r,i=a.prop("tagName").toLowerCase(),d=t.$scope;if("input"!==i&&"textarea"!==i&&"button"!==i&&"select"!==i){for(;a&&a[0]&&a[0]!==t.element;){if(n.nodrag(a))return;a=a.parent()}if(e.uiTreeDragging=!0,e.originalEvent&&(e.originalEvent.uiTreeDragging=!0),e.preventDefault(),r=l.getScopeNode(),t.dragInfo=n.dragInfo(r),d.$callbacks.beforeDrag(r,t.dragInfo)){t.firstMoving=!0,d.setDragging(t.dragInfo);var o=n.eventObj(e);t.pos=n.positionStarted(o,r.$element),r.isTable?t.dragElm=angular.element(t.$window.document.createElement("table")).addClass(d.$class.tree).addClass(d.$class.drag).addClass(d.$tree_class):t.dragElm=angular.element(t.$window.document.createElement("ul")).addClass(d.$class.drag).addClass("tree-dnd-nodes").addClass(d.$tree_class),t.dragElm.css({width:n.width(r.$element)+"px","z-index":9995}),t.offsetEdge=0;var s,_,c,u=n.width(r.$element),g=r,f=g.$element,p=!!d.enabledCollapse,m=!1;g.isTable?(t.offsetEdge=t.dragInfo.node.__level__-1,_=angular.element(document.createElement("tbody")),c=angular.element(document.createDocumentFragment()),d.for_all_descendants(t.dragInfo.node,function(e,a){return g=d.getScope(e),f=g&&g.$element,g&&f&&(m||(s=f.clone(),n.replaceIndent(d,s,e.__level__-t.offsetEdge,"padding-left"),c.append(s),p&&(m=!0),d.enabledMove&&d.$class.hidden&&(!a||e.__visible__||a.__visible__&&a.__expanded__)&&f.addClass(d.$class.hidden))),m||e.__visible__===!1||e.__expanded__===!1},null,!p),_.append(c),t.dragElm.append(_)):(s=f.clone(),p&&s[0].querySelector("[tree-dnd-nodes]").remove(),t.dragElm.append(s),d.enabledMove&&d.$class.hidden&&f.addClass(d.$class.hidden)),t.dragElm.css({left:o.pageX-t.pos.offsetX+d.$callbacks.calsIndent(t.offsetEdge+1,!0,!0)+"px",top:o.pageY-t.pos.offsetY+"px"}),t.$document.find("body").append(t.dragElm),d.$callbacks.droppable()&&(t.placeElm=d.initPlace(r.$element,t.dragElm),r.isTable&&n.replaceIndent(d,t.placeElm,t.dragInfo.node.__level__),t.placeElm.css("width",u)),d.showPlace(),d.targeting=!0,d.enabledStatus&&(d.refreshStatus(),d.setPositionStatus(e)),angular.element(t.$document).bind("touchend",t.dragEndEvent),angular.element(t.$document).bind("touchcancel",t.dragEndEvent),angular.element(t.$document).bind("touchmove",t.dragMoveEvent),angular.element(t.$document).bind("mouseup",t.dragEndEvent),angular.element(t.$document).bind("mousemove",t.dragMoveEvent),angular.element(t.$document).bind("mouseleave",t.dragCancelEvent),t.document_height=Math.max(t.body.scrollHeight,t.body.offsetHeight,t.html.clientHeight,t.html.scrollHeight,t.html.offsetHeight),t.document_width=Math.max(t.body.scrollWidth,t.body.offsetWidth,t.html.clientWidth,t.html.scrollWidth,t.html.offsetWidth)}}}}}function l(e,a){var l=a.$scope;if(!a.dragStarted)return void(a.dragDelaying||(a.dragStarted=!0,l.$safeApply(function(){l.$callbacks.dragStart(a.dragInfo)})));if(a.dragElm){e.preventDefault(),a.$window.getSelection?a.$window.getSelection().removeAllRanges():a.$window.document.selection&&a.$window.document.selection.empty();var r=n.eventObj(e),i=r.pageX-a.pos.offsetX,d=r.pageY-a.pos.offsetY;0>i&&(i=0),0>d&&(d=0),d+10>a.document_height&&(d=a.document_height-10),i+10>a.document_width&&(i=a.document_width-10),a.dragElm.css({left:i+l.$callbacks.calsIndent(a.offsetEdge+1,!0,!0)+"px",top:d+"px"}),l.enabledStatus&&l.setPositionStatus(e);var o=window.pageYOffset||a.$window.document.documentElement.scrollTop,s=o+(window.innerHeight||a.$window.document.clientHeight||a.$window.document.clientHeight);if(sr.pageY&&window.scrollBy(0,-10),n.positionMoved(e,a.pos,a.firstMoving),a.firstMoving)return void(a.firstMoving=!1);var _,c,u,g,f,p,m,h,b,v,$=r.pageX-a.$window.document.body.scrollLeft,y=r.pageY-(window.pageYOffset||a.$window.document.documentElement.scrollTop),D=!0,x=!0,E=a.dragInfo,T=E.move,w=E.node,C=E.drop,S=E.target,k=t(e,a);if(!k){if(_=angular.element(a.$window.document.elementFromPoint($,y)),c=_.scope(),!c||!c.$callbacks||!c.$callbacks.droppable())return;if(v=function(){return S=c.getScopeTree(),h=E.target,E.target!==S&&(h.hidePlace(),h.targeting=!1,S.targeting=!0,E.target=S,a.placeElm=S.initPlace(c.$element,a.dragElm),h=null,p=!0),!0},angular.isFunction(c.getScopeNode)){if(c=c.getScopeNode(),!v())return}else{if("TreeDnDNodes"!==c.$type&&"TreeDnD"!==c.$type)return;if(!c.tree_nodes)return;if(0===c.tree_nodes.length){if(!v())return;f=!0}}}if((a.pos.dirAx&&!p||k)&&(x=!1,c=E.scope),!c.$element&&!c)return;if(f)T.parent=null,T.pos=0,C=null;else if(x){if(_=c.$element,angular.isUndefinedOrNull(_))return;if(g=n.offset(_),c.horizontal&&!c.isTable)u=r.pageXg.top+M)return;u=r.pageY=S.dragBorder))return;if(a.pos.distAxX=0,a.pos.distX>0){if(b=C,!b){if(!(T.pos-1>=0))return;b=T.parent.__children__[T.pos-1]}if(E.drag===E.target&&b===w&&l.enabledMove&&(b=S.getPrevSibling(b)),!b||!b.__visible__)return;var P=b.__children__.length;T.parent=b,T.pos=P,C=P>0?b.__children__[P-1]:null}else{if(!(a.pos.distX<0))return;if(h=T.parent,!h||!(0===h.__children__.length||h.__children__.length-1r;r++)o.for_all_descendants(t.treeData[r],n)},collapse_all:function(){for(i=t.treeData.length,r=0;i>r;r++)o.for_all_descendants(t.treeData[r],e)},remove_node:function(e){e=e||o.selected_node,"object"==typeof e&&(l=null!==e.__parent_real__?o.get_parent(e).__children__:t.treeData,l.splice(e.__index__,1),o.reload_data(),o.selected_node===e&&(o.selected_node=null))},expand_node:function(e){return e=e||o.selected_node,"object"==typeof e&&e.__expanded__?(e.__expanded__=!0,e):void 0},collapse_node:function(e){return e=e||o.selected_node,"object"==typeof e?(e.__expanded__=!1,e):void 0},get_selected_node:function(){return o.selected_node},get_first_node:function(){return i=t.treeData.length,i>0?t.treeData[0]:null},get_children:function(e){return e.__children__},get_siblings:function(e){return e=e||o.selected_node,"object"==typeof e?(l=o.get_parent(e),a=l?l.__children__:t.treeData):void 0},get_next_sibling:function(e){return e=e||o.selected_node,"object"==typeof e&&(a=o.get_siblings(e),d=a.length,e.__index__0?a[e.__index__-1]:void 0},get_first_child:function(e){return e=e||o.selected_node,"object"==typeof e&&(a=e.__children__,a&&a.length>0)?e.__children__[0]:null},get_closest_ancestor_next_sibling:function(e){return e=e||o.selected_node,(a=o.get_next_sibling(e))?a:(l=o.get_parent(e),o.get_closest_ancestor_next_sibling(l))},get_next_node:function(e){return e=e||o.selected_node,"object"==typeof e?(a=o.get_first_child(e),a?a:o.get_closest_ancestor_next_sibling(e)):void 0},get_prev_node:function(e){return e=e||o.selected_node,"object"==typeof e?(a=o.get_prev_sibling(e))?o.get_last_descendant(a):l=o.get_parent(e):void 0},get_last_descendant:t.getLastDescendant,select_parent_node:function(e){return e=e||o.selected_node,"object"==typeof e&&(l=o.get_parent(e))?o.select_node(l):void 0},select_first_node:function(){var e=o.get_first_node();return o.select_node(e)},select_next_sibling:function(e){return e=e||o.selected_node,"object"==typeof e&&(a=o.get_next_sibling(e))?o.select_node(a):void 0},select_prev_sibling:function(e){return e=e||o.selected_node,"object"==typeof e&&(a=o.get_prev_sibling(e))?o.select_node(a):void 0},select_next_node:function(e){return e=e||o.selected_node,"object"==typeof e&&(a=o.get_next_node(e))?o.select_node(a):void 0},select_prev_node:function(e){return e=e||o.selected_node,"object"==typeof e&&(a=o.get_prev_node(e))?o.select_node(a):void 0}};return angular.extend(t.tree,o),t.tree}var a,l,r,i;return t}),angular.module("template/TreeDnD/TreeDnD.html",[]).run(["$templateCache",function(e){e.put("template/TreeDnD/TreeDnD.html",[''," "," ",' ",' "," "," "," ",' "," ",' "," "," ","
'," {{expandingProperty.displayName || expandingProperty.field || expandingProperty}}"," '," {{col.displayName || col.field}}","
'," ",' '," "," {{node[expandingProperty.field] || node[expandingProperty]}}"," '," {{node[col.field]}}","
"].join("\n")),e.put("template/TreeDnD/TreeDnDStatusCopy.html",''),e.put("template/TreeDnD/TreeDnDStatusMove.html",'')}])}(); +//# sourceMappingURL=ng-tree-dnd.min.js.map diff --git a/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.js.map b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.js.map new file mode 100644 index 0000000..2ec126f --- /dev/null +++ b/src/main/resources/static/module/angular-tree-dnd/ng-tree-dnd.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["ng-tree-dnd.js"],"names":["fnInitTreeDnD","$timeout","$http","$compile","$parse","$window","$document","$templateCache","$TreeDnDTemplate","$TreeDnDClass","$TreeDnDHelper","$TreeDnDPlugin","$TreeDnDViewport","fnController","$scope","$element","$attrs","timeLoadData","treeData","tmpTreeData","reload_data","timeReloadData","check_exist_attr","attrs","existAttr","isAnd","angular","isUndefinedOrNull","isUndefined","isArray","for_each_attrs","exist","i","len","length","passed","generateWatch","type","nameAttr","valDefault","nameScope","fnNotExist","fnAfter","fnBefore","isFunction","$watch","val","indexOf","$safeApply","fn","phase","this","$root","$$phase","$apply","getExpandOn","_len","_firstNode","_keys","Object","keys","_regex","RegExp","test","expandingProperty","getColDefs","_col_defs","push","field","colDefinitions","do_f","root","node","parent","parent_real","level","visible","index","_i","_icon","_index_real","_dept","_hashKey","__children__","__parent_real__","__parent__","__expanded__","expandLevel","__index__","__index_real__","__level__","__icon__","__icon_class__","$class","icon","__visible__","__uid__","Math","random","getHash","__hashKey__","primary_key","__dept__","init_data","data","isDefined","tree_nodes","oData","_data","_tree_nodes","expandOn","columnDefs","orderBy","_fnInitOrderBy","filter","_fnInitFilter","filterOptions","_deptTotal","indent","indent_plus","indent_unit","$tree_class","$type","$globals","copy","extend","1","iconExpand","0","iconCollapse","-1","iconLeaf","for_all_descendants","checkSibling","_nodes","getLastDescendant","last_child","n","tree","selected_node","getElementChilds","element","querySelector","onClick","on_click","setTimeout","onSelect","select_node","on_select","passedExpand","_clone","toggleExpand","fnCallback","$callbacks","expand","_fnGetHash","_fnSetHash","setHash","accept","dragInfo","moveTo","isChanged","dropEnabled","calsIndent","skipUnit","skipEdge","unit","edge","droppable","draggable","dragEnabled","beforeDrop","event","changeKey","_key","__selected__","replace","clone","_this","remove","delayReload","temp","splice","clearInfo","__inited__","add","pos","deleteScope","scope","_hash","setScope","getScope","enableDrag","enableDrop","placeElm","horizontal","dragDelay","enabledMove","statusMove","enabledHotkey","enabledCollapse","statusElm","dragging","beforeDrag","scopeDrag","dragStop","info","changed","drag","target","dropped","pass","_node","_nodeAdd","_move","move","_parent","_parentRemove","_parentAdd","isMove","dragStart","dragMove","setDragging","enableMove","enableStatus","enabledStatus","hideStatus","addClass","hidden","refreshStatus","statusElmOld","getMove","getCopy","attr","find","append","removeClass","setPositionStatus","e","css","left","pageX","top","pageY","z-index","status","targeting","getPrevSibling","_index","getNode","initPlace","dragElm","isTable","document","createElement","_len_down","empty","place","height","parentNode","insertBefore","hidePlace","showPlace","getScopeTree","hiddenChild","nodeScope","_fnGetControl","w","_curW","_typeW","_nameW","_defaultW","_scopeW","_NotW","_AfterW","_BeforeW","_defaultFilterOption","showParent","showChild","beginAnd","_watches","isHotkey","templateCopy","_url","get","setCopy","templateMove","setMove","treeClass","trim","$tree","colDefs","filters","_passed","_iF","_keysF","_lenF","enabledFilter","option","primaryKey","indentUnit","optCallbacks","forEach","value","key","lenW","equals","updateLimit","$TreeLimit","fnCompile","tElement","$_Template","_element","html","_fnInitDrag","ready","checkTreeTable","template","attrInclude","elemNode","treeInclude","cache","success","tempDiv","innerHTML","setTemplate","templateNode","promiseCheck","then","templateUrl","getPath","restrict","controller","compile","fnInitTreeDnDViewport","$q","update","viewportRect","width","eWindow","prop","documentElement","clientWidth","clientHeight","body","scrollTop","scrollLeft","isUpdating","isRender","updateAgain","recursivePromise","item","number","items","renderTime","cancel","setViewport","viewport","getViewport","updateDelayed","updateTimeout","nodeTemplate","getItems","$initViewport","on","module","constant","nodes","handle","directive","link","new_val","compileReplace","replaceWith","fnLink","fnWatchNode","newVal","oldVal","nodeOf","keyNode","first","parentReal","_childs","hashKey","childsElem","$node_class","enabledDnD","treeDndNode","getData","getScopeNode","objexpr","objprops","keyO","lenO","skipAttr","keepAttr","lenKeep","join","$on","$nodes_class","$inject","factory","$filter","options","fieldChild","parentPassed","_nodePassed","_childPassed","_filter_index","filter_index","_fnCheck","callback","err","_fnProccess","condition","for_each_filter","_iO","_keysO","_lenO","_callback","conditions","_fnAfter","isNodePassed","isChildPassed","isParentPassed","__filtered__","__filtered_visible__","__filtered_index__","_fnBefore","_fnBeforeClear","_fnConvert","_filter","_state","isObject","fnInitFilter","keyChild","_fnOrderBy","name","fnOrderBy","_fnOrder","list","_fnMain","isString","_$initConvert","line2tree","parentKey","parentId","rootIds","_primary","treeObjs","tree2tree","access_child","containKey","_copy","_child","_tree","_$helper","nodrag","targetElm","eventObj","obj","undefined","targetTouches","originalEvent","drop","offset","boundingClientRect","getBoundingClientRect","pageYOffset","pageXOffset","positionStarted","offsetX","offsetY","startX","lastX","startY","lastY","nowX","nowY","distX","distY","dirAx","dirX","dirY","lastDirX","lastDirY","distAxX","distAxY","positionMoved","firstMoving","newAx","abs","moving","replaceIndent","children","$injector","_fnget","has","templatePath","copyPath","movePath","scopes","_$init","path","$id","_fnPlaceHolder","$params","_offset","_fnDragStart","hasTouch","button","which","uiTreeDragging","eventElm","eventScope","dragScope","eventElmTagName","toLowerCase","_$scope","preventDefault","offsetEdge","_tbody","_frag","_width","_scope","_needCollapse","_copied","createDocumentFragment","bind","dragEndEvent","dragMoveEvent","dragCancelEvent","document_height","max","scrollHeight","offsetHeight","document_width","scrollWidth","offsetWidth","_fnDragMove","dragStarted","dragDelaying","getSelection","removeAllRanges","selection","leftElmPos","topElmPos","top_scroll","window","bottom_scroll","innerHeight","scrollBy","targetScope","targetBefore","targetOffset","isEmpty","isSwapped","_target","fnSwapTree","targetX","targetY","isVeritcal","_info","_drag","_drop","treeScope","isHolder","elementFromPoint","_height","_prev","dragBorder","after","prepend","_fnDragEnd","clearData","$$apply","_status","_fnBindDrag","unbind","_fnDragStartEvent","dragTimer","_fnKeydownHandler","keyCode","shiftKey","_fnKeyupHandler","bindDrag","dragEnd","keydownHandler","keyupHandler","fnSetCollapse","fnSetExpand","expand_all_parents","deselect_node","get_parent","for_all_ancestors","child","collapse_all_parents","add_node","new_node","add_node_root","expand_all","collapse_all","remove_node","expand_node","collapse_node","get_selected_node","get_first_node","get_children","get_siblings","get_next_sibling","get_prev_sibling","get_first_child","get_closest_ancestor_next_sibling","get_next_node","get_prev_node","get_last_descendant","select_parent_node","select_first_node","firstNode","select_next_sibling","select_prev_sibling","select_next_node","select_prev_node","run","put"],"mappings":"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","file":"ng-tree-dnd.min.js","sourcesContent":["/**\n * The MIT License (MIT)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n * @preserve\n */\n\n/**\n * Implementing TreeDnD & Event DrapnDrop (allow drag multi tree-table include all type: table, ol, ul)\n * Demo: http://thienhung1989.github.io/angular-tree-dnd\n * Github: https://github.com/thienhung1989/angular-tree-dnd\n * @version 3.0.5\n * @preserve\n * (c) 2015 Nguyuễn Thiện Hùng - \n */\n(function () {\n 'use strict';\n angular.isUndefinedOrNull = isUndefinedOrNull;\n\n angular.isDefined = isDefined;\n\n angular.module('ntt.TreeDnD', ['template/TreeDnD/TreeDnD.html'])\n .constant(\n '$TreeDnDClass', {\n tree: 'tree-dnd',\n empty: 'tree-dnd-empty',\n hidden: 'tree-dnd-hidden',\n node: 'tree-dnd-node',\n nodes: 'tree-dnd-nodes',\n handle: 'tree-dnd-handle',\n place: 'tree-dnd-placeholder',\n drag: 'tree-dnd-drag',\n status: 'tree-dnd-status',\n icon: {\n '1': 'glyphicon glyphicon-minus',\n '0': 'glyphicon glyphicon-plus',\n '-1': 'glyphicon glyphicon-file'\n }\n }\n );angular.module('ntt.TreeDnD')\n .directive(\n 'compile', [\n '$compile', function ($compile) {\n return {\n restrict: 'A',\n link: function (scope, element, attrs) {\n scope.$watch(\n attrs.compile, function (new_val) {\n if (new_val) {\n if (angular.isFunction(element.empty)) {\n element.empty();\n } else {\n element.html('');\n }\n\n element.append($compile(new_val)(scope));\n }\n }\n );\n }\n };\n }]\n)\n .directive(\n 'compileReplace', [\n '$compile', function ($compile) {\n return {\n restrict: 'A',\n link: function (scope, element, attrs) {\n scope.$watch(\n attrs.compileReplace, function (new_val) {\n if (new_val) {\n element.replaceWith($compile(new_val)(scope));\n }\n }\n );\n }\n };\n }]\n);\n\nangular.module('ntt.TreeDnD')\r .directive(\r 'treeDndNodeHandle', function () {\r return {\r restrict: 'A',\r scope: true,\r link: function (scope, element, attrs) {\r scope.$type = 'TreeDnDNodeHandle';\r if (scope.$class.handle) {\r element.addClass(scope.$class.handle);\r }\r }\r };\r }\r);\n\nangular.module('ntt.TreeDnD')\n .directive(\n 'treeDndNode', ['$TreeDnDViewport', '$timeout', function ($TreeDnDViewport, $timeout) {\n return {\n restrict: 'A',\n replace: true,\n link: fnLink\n };\n function fnLink(scope, element, attrs) {\n\n scope.$node_class = '';\n\n if (scope.$class.node) {\n element.addClass(scope.$class.node);\n scope.$node_class = scope.$class.node;\n }\n var enabledDnD = typeof scope.dragEnabled === 'boolean' || typeof scope.dropEnabled === 'boolean',\n keyNode = attrs.treeDndNode,\n first = true,\n childsElem;\n\t\t\t$TreeDnDViewport.add(scope, element);\n\n if (enabledDnD) {\n scope.$type = 'TreeDnDNode';\n\n scope.getData = function () {\n return scope[keyNode];\n };\n }\n\n scope.$element = element;\n scope[keyNode].__inited__ = true;\n\n scope.getElementChilds = function () {\n return angular.element(element[0].querySelector('[tree-dnd-nodes]'));\n };\n\n scope.setScope(scope, scope[keyNode]);\n\n scope.getScopeNode = function () {\n return scope;\n };\n\n var objprops = [],\n objexpr,\n i, keyO = Object.keys(scope[keyNode]),\n lenO = keyO.length,\n hashKey = scope[keyNode].__hashKey__,\n skipAttr = [\n '__visible__',\n '__children__',\n '__level__',\n '__index__',\n '__index_real__',\n\n '__parent__',\n '__parent_real__',\n '__dept__',\n '__icon__',\n '__icon_class__'\n ],\n keepAttr = [\n '__expanded__'\n ],\n lenKeep = keepAttr.length;\n\n // skip __visible__\n for (i = 0; i < lenO + lenKeep; i++) {\n if (i < lenO) {\n if (skipAttr.indexOf(keyO[i]) === -1) {\n objprops.push(keyNode + '.' + keyO[i]);\n }\n } else {\n if (keyO.indexOf(keepAttr[i - lenO]) === -1) {\n objprops.push(keyNode + '.' + keepAttr[i - lenO]);\n }\n }\n }\n\n objexpr = '[' + objprops.join(',') + ']';\n\n scope.$watch(objexpr, fnWatchNode, true);\n\n scope.$on('$destroy', function () {\n scope.deleteScope(scope, scope[keyNode]);\n });\n\n function fnWatchNode(newVal, oldVal, scope) {\n\n\t\t\t\tvar nodeOf = scope[keyNode],\n _icon;\n\n if (first) {\n _icon = nodeOf.__icon__;\n nodeOf.__icon_class__ = scope.$class.icon[_icon];\n } else {\n\n var parentReal = nodeOf.__parent_real__,\n parentNode = scope.tree_nodes[parentReal] || null,\n _childs = nodeOf.__children__,\n _len = _childs.length,\n _i;\n\n if (!nodeOf.__inited__) {\n nodeOf.__inited__ = true;\n }\n\n if (nodeOf.__hashKey__ !== hashKey) {\n // clear scope in $globals\n scope.deleteScope(scope, nodeOf);\n\n // add new scope into $globals\n scope.setScope(scope, nodeOf);\n hashKey = nodeOf.__hashKey__;\n }\n\n if (parentNode && (!parentNode.__expanded__ || !parentNode.__visible__)) {\n element.addClass(scope.$class.hidden);\n nodeOf.__visible__ = false;\n } else {\n element.removeClass(scope.$class.hidden);\n nodeOf.__visible__ = true;\n }\n\n if (_len === 0) {\n _icon = -1;\n } else {\n if (nodeOf.__expanded__) {\n _icon = 1;\n } else {\n _icon = 0;\n }\n }\n\n nodeOf.__icon__ = _icon;\n nodeOf.__icon_class__ = scope.$class.icon[_icon];\n\n if (scope.isTable) {\n for (_i = 0; _i < _len; _i++) {\n scope.for_all_descendants(_childs[_i], scope.hiddenChild, nodeOf, true);\n }\n } else {\n if (!childsElem) {\n childsElem = scope.getElementChilds();\n }\n\n if (nodeOf.__expanded__) {\n childsElem.removeClass(scope.$class.hidden);\n } else {\n childsElem.addClass(scope.$class.hidden);\n }\n }\n\n }\n\n\t\t\t\tfirst = false;\n\n }\n }\n }]\n);\n\nangular.module('ntt.TreeDnD')\n .directive(\n 'treeDndNodes', function () {\n return {\n restrict: 'A',\n replace: true,\n link: function (scope, element/*, attrs*/) {\n scope.$type = 'TreeDnDNodes';\n\n if (scope.$class.nodes) {\n element.addClass(scope.$class.nodes);\n scope.$nodes_class = scope.$class.nodes;\n } else {\n scope.$nodes_class = '';\n }\n }\n };\n }\n);\n\nangular.module('ntt.TreeDnD')\n .directive(\n 'treeDnd', fnInitTreeDnD);\n\nfnInitTreeDnD.$inject = [\n '$timeout', '$http', '$compile', '$parse', '$window', '$document', '$templateCache',\n '$TreeDnDTemplate', '$TreeDnDClass', '$TreeDnDHelper', '$TreeDnDPlugin', '$TreeDnDViewport'\n];\n\nfunction fnInitTreeDnD($timeout, $http, $compile, $parse, $window, $document, $templateCache,\n $TreeDnDTemplate, $TreeDnDClass, $TreeDnDHelper, $TreeDnDPlugin, $TreeDnDViewport\n) {\n return {\n restrict: 'E',\n scope: true,\n replace: true,\n controller: ['$scope', '$element', '$attrs', fnController],\n compile: fnCompile\n };\n\n function fnController($scope, $element, $attrs) {\n $scope.indent = 20;\n $scope.indent_plus = 15;\n $scope.indent_unit = 'px';\n $scope.$tree_class = 'table';\n $scope.primary_key = '__uid__';\n\n $scope.$type = 'TreeDnD';\n // $scope.enabledFilter = null;\n $scope.colDefinitions = [];\n $scope.$globals = {};\n $scope.$class = {};\n\n $scope.treeData = [];\n $scope.tree_nodes = [];\n\n $scope.$class = angular.copy($TreeDnDClass);\n angular.extend(\n $scope.$class.icon, {\n '1': $attrs.iconExpand || 'glyphicon glyphicon-minus',\n '0': $attrs.iconCollapse || 'glyphicon glyphicon-plus',\n '-1': $attrs.iconLeaf || 'glyphicon glyphicon-file'\n }\n );\n\n $scope.for_all_descendants = function (node, fn, parent, checkSibling) {\n if (angular.isFunction(fn)) {\n var _i, _len, _nodes;\n\n if (fn(node, parent)) {\n // have error or need ignore children\n return false;\n }\n _nodes = node.__children__;\n _len = _nodes ? _nodes.length : 0;\n for (_i = 0; _i < _len; _i++) {\n if (!$scope.for_all_descendants(_nodes[_i], fn, node) && !checkSibling) {\n // skip sibling of node checking\n return false;\n }\n }\n }\n // succeed then continue\n return true;\n };\n\n $scope.getLastDescendant = function (node) {\n var last_child, n;\n if (!node) {\n node = $scope.tree ? $scope.tree.selected_node : false;\n }\n if (node === false) {\n return false;\n }\n n = node.__children__.length;\n if (n === 0) {\n return node;\n } else {\n last_child = node.__children__[n - 1];\n return $scope.getLastDescendant(last_child);\n }\n };\n\n $scope.getElementChilds = function () {\n return angular.element($element[0].querySelector('[tree-dnd-nodes]'));\n };\n\n $scope.onClick = function (node) {\n if (angular.isDefined($scope.tree) && angular.isFunction($scope.tree.on_click)) {\n // We want to detach from Angular's digest cycle so we can\n // independently measure the time for one cycle.\n setTimeout(\n function () {\n $scope.tree.on_click(node);\n }, 0\n );\n }\n };\n\n $scope.onSelect = function (node) {\n if (angular.isDefined($scope.tree)) {\n if (node !== $scope.tree.selected_node) {\n $scope.tree.select_node(node);\n }\n\n if (angular.isFunction($scope.tree.on_select)) {\n setTimeout(\n function () {\n $scope.tree.on_select(node);\n }, 0\n );\n }\n }\n };\n\n var passedExpand, _clone;\n $scope.toggleExpand = function (node, fnCallback) {\n passedExpand = true;\n if (angular.isFunction(fnCallback) && !fnCallback(node)) {\n passedExpand = false;\n } else if (angular.isFunction($scope.$callbacks.expand) && !$scope.$callbacks.expand(node)) {\n passedExpand = false;\n }\n\n if (passedExpand) {\n if (node.__children__.length > 0) {\n node.__expanded__ = !node.__expanded__;\n }\n }\n };\n\n\n var _fnGetHash = function (node) {\n return '#' + node.__parent__ + '#' + node[$scope.primary_key];\n },\n _fnSetHash = function (node) {\n var _hashKey = _fnGetHash(node);\n if (angular.isUndefinedOrNull(node.__hashKey__) || node.__hashKey__ !== _hashKey) {\n node.__hashKey__ = _hashKey;\n }\n return node;\n };\n $scope.getHash = _fnGetHash;\n $scope.$callbacks = {\n getHash: _fnGetHash,\n setHash: _fnSetHash,\n for_all_descendants: $scope.for_all_descendants,\n /*expand: function (node) {\n return true;\n },*/\n accept: function (dragInfo, moveTo, isChanged) {\n return $scope.dropEnabled === true;\n },\n calsIndent: function (level, skipUnit, skipEdge) {\n var unit = 0,\n edge = skipEdge ? 0 : $scope.indent_plus;\n if (!skipUnit) {\n unit = $scope.indent_unit ? $scope.indent_unit : 'px';\n }\n\n if (level - 1 < 1) {\n return edge + unit;\n } else {\n return $scope.indent * (level - 1) + edge + unit;\n }\n },\n droppable: function () {\n return $scope.dropEnabled === true;\n },\n draggable: function () {\n return $scope.dragEnabled === true;\n },\n beforeDrop: function (event) {\n return true;\n },\n changeKey: function (node) {\n var _key = node.__uid__;\n node.__uid__ = Math.random();\n if (node.__selected__) {\n delete node.__selected__;\n }\n\n if ($scope.primary_key !== '__uid__') {\n _key = '' + node[$scope.primary_key];\n _key = _key.replace(/_#.+$/g, '') + '_#' + node.__uid__;\n\n node[$scope.primary_key] = _key;\n }\n // delete(node.__hashKey__);\n },\n clone: function (node, _this) {\n _clone = angular.copy(node);\n this.for_all_descendants(_clone, this.changeKey);\n return _clone;\n },\n remove: function (node, parent, _this, delayReload) {\n var temp = parent.splice(node.__index__, 1)[0];\n if (!delayReload) {\n $scope.reload_data();\n }\n return temp;\n },\n clearInfo: function (node) {\n delete node.__inited__;\n delete node.__visible__;\n\n // always changed after call reload_data\n //delete node.__hashKey__;\n },\n add: function (node, pos, parent, _this) {\n // clearInfo\n this.for_all_descendants(node, this.clearInfo);\n if (parent) {\n if (parent.length > -1) {\n if (pos > -1) {\n parent.splice(pos, 0, node);\n } else {\n // todo If children need load crazy\n parent.push(node);\n }\n } else {\n parent.push(node);\n }\n }\n }\n };\n\n $scope.deleteScope = function (scope, node) {\n var _hash = node.__hashKey__;\n if ($scope.$globals[_hash] && $scope.$globals[_hash] === scope) {\n delete $scope.$globals[_hash];\n }\n };\n\n $scope.setScope = function (scope, node) {\n var _hash = node.__hashKey__;\n if ($scope.$globals[_hash] !== scope) {\n $scope.$globals[_hash] = scope;\n }\n };\n\n $scope.getScope = function (node) {\n if (node) {\n var _hash = node.__hashKey__;\n //var _hash = typeof node === 'string' ? node : node.__hashKey__;\n return $scope.$globals[_hash];\n }\n return $scope;\n };\n\n if ($attrs.enableDrag || $attrs.enableDrop) {\n $scope.placeElm = null;\n // $scope.dragBorder = 30;\n $scope.dragEnabled = null;\n $scope.dropEnabled = null;\n $scope.horizontal = null;\n\n if ($attrs.enableDrag) {\n\n $scope.dragDelay = 0;\n $scope.enabledMove = true;\n $scope.statusMove = true;\n $scope.enabledHotkey = false;\n $scope.enabledCollapse = null;\n $scope.statusElm = null;\n $scope.dragging = null;\n\n angular.extend(\n $scope.$callbacks, {\n beforeDrag: function (scopeDrag) {\n return true;\n },\n dragStop: function (info, passed) {\n if (!info || !info.changed && info.drag.enabledMove || !passed) {\n return null;\n }\n\n info.target.reload_data();\n\n if (info.target !== info.drag && info.drag.enabledMove) {\n info.drag.reload_data();\n }\n },\n dropped: function (info, pass) {\n if (!info) {\n return null;\n }\n\n var _node = info.node,\n _nodeAdd = null,\n _move = info.move,\n _parent = null,\n _parentRemove = info.parent || info.drag.treeData,\n _parentAdd = _move.parent || info.target.treeData,\n isMove = info.drag.enabledMove;\n\n if (!info.changed && isMove) {\n return false;\n }\n\n if (info.target.$callbacks.accept(info, info.move, info.changed)) {\n if (isMove) {\n _parent = _parentRemove;\n if (angular.isDefined(_parent.__children__)) {\n _parent = _parent.__children__;\n }\n\n _nodeAdd = info.drag.$callbacks.remove(\n _node,\n _parent,\n info.drag.$callbacks,\n true // delay reload\n );\n } else {\n _nodeAdd = info.drag.$callbacks.clone(_node, info.drag.$callbacks);\n }\n\n // if node dragging change index in sample node parent\n // and index node decrement\n if (isMove &&\n info.drag === info.target &&\n _parentRemove === _parentAdd &&\n _move.pos >= info.node.__index__) {\n _move.pos--;\n }\n\n _parent = _parentAdd;\n if (_parent.__children__) {\n _parent = _parent.__children__;\n }\n\n info.target.$callbacks.add(\n _nodeAdd,\n _move.pos,\n _parent,\n info.drag.$callbacks\n );\n\n return true;\n }\n\n return false;\n },\n dragStart: function (event) {\n },\n dragMove: function (event) {\n }\n }\n );\n\n $scope.setDragging = function (dragInfo) {\n $scope.dragging = dragInfo;\n };\n\n $scope.enableMove = function (val) {\n if (typeof val === 'boolean') {\n $scope.enabledMove = val;\n } else {\n $scope.enabledMove = true;\n }\n };\n\n if ($attrs.enableStatus) {\n $scope.enabledStatus = false;\n\n $scope.hideStatus = function () {\n if ($scope.statusElm) {\n $scope.statusElm.addClass($scope.$class.hidden);\n }\n };\n\n $scope.refreshStatus = function () {\n if (!$scope.dragging) {\n return;\n }\n\n if ($scope.enabledStatus) {\n var statusElmOld = $scope.statusElm;\n if ($scope.enabledMove) {\n $scope.statusElm = angular.element($TreeDnDTemplate.getMove($scope));\n } else {\n $scope.statusElm = angular.element($TreeDnDTemplate.getCopy($scope));\n }\n\n if (statusElmOld !== $scope.statusElm) {\n if (statusElmOld) {\n $scope.statusElm.attr('class', statusElmOld.attr('class'));\n $scope.statusElm.attr('style', statusElmOld.attr('style'));\n statusElmOld.remove();\n }\n $document.find('body').append($scope.statusElm);\n\n }\n\n $scope.statusElm.removeClass($scope.$class.hidden);\n }\n };\n\n $scope.setPositionStatus = function (e) {\n if ($scope.statusElm) {\n $scope.statusElm.css(\n {\n 'left': e.pageX + 10 + 'px',\n 'top': e.pageY + 15 + 'px',\n 'z-index': 9999\n }\n );\n $scope.statusElm.addClass($scope.$class.status);\n }\n };\n }\n }\n\n $scope.targeting = false;\n\n $scope.getPrevSibling = function (node) {\n if (node && node.__index__ > 0) {\n var _parent, _index = node.__index__ - 1;\n\n if (angular.isDefined(node.__parent_real__)) {\n _parent = $scope.tree_nodes[node.__parent_real__];\n return _parent.__children__[_index];\n }\n return $scope.treeData[_index];\n\n }\n return null;\n };\n\n $scope.getNode = function (index) {\n if (angular.isUndefinedOrNull(index)) {\n return null;\n }\n return $scope.tree_nodes[index];\n };\n\n $scope.initPlace = function (element, dragElm) {\n\n if (!$scope.placeElm) {\n if ($scope.isTable) {\n $scope.placeElm = angular.element($window.document.createElement('tr'));\n var _len_down = $scope.colDefinitions.length;\n $scope.placeElm.append(\n angular.element($window.document.createElement('td'))\n .addClass($scope.$class.empty)\n .addClass('indented')\n .addClass($scope.$class.place)\n );\n while (_len_down-- > 0) {\n $scope.placeElm.append(\n angular.element($window.document.createElement('td'))\n .addClass($scope.$class.empty)\n .addClass($scope.$class.place)\n );\n }\n } else {\n $scope.placeElm = angular.element($window.document.createElement('li'))\n .addClass($scope.$class.empty)\n .addClass($scope.$class.place);\n }\n\n }\n\n if (dragElm) {\n $scope.placeElm.css('height', $TreeDnDHelper.height(dragElm) + 'px');\n }\n\n if (element) {\n element[0].parentNode.insertBefore($scope.placeElm[0], element[0]);\n } else {\n $scope.getElementChilds().append($scope.placeElm);\n }\n\n return $scope.placeElm;\n };\n\n $scope.hidePlace = function () {\n if ($scope.placeElm) {\n $scope.placeElm.addClass($scope.$class.hidden);\n }\n };\n\n $scope.showPlace = function () {\n if ($scope.placeElm) {\n $scope.placeElm.removeClass($scope.$class.hidden);\n }\n };\n\n $scope.getScopeTree = function () {\n return $scope;\n };\n\n }\n\n $scope.$safeApply = $safeApply;\n\n\n $scope.hiddenChild = function fnHiddenChild(node, parent) {\n var nodeScope = $scope.getScope(node);\n if (nodeScope) {\n if (parent && parent.__expanded__ && parent.__visible__) {\n nodeScope.$element.removeClass($scope.$class.hidden);\n node.__visible__ = true;\n } else {\n nodeScope.$element.addClass($scope.$class.hidden);\n node.__visible__ = false;\n }\n } else {\n // show node & init scope\n if (parent && parent.__expanded__ && parent.__visible__) {\n node.__visible__ = true;\n } else {\n node.__visible__ = false;\n }\n }\n\n // skip all child hiding... if not expaned\n return node.__expanded__ === false;\n }\n var _fnInitFilter,\n _fnInitOrderBy,\n _fnGetControl,\n _defaultFilterOption = {\n showParent: true,\n showChild: false,\n beginAnd: true\n },\n tree,\n _watches = [\n [\n 'enableDrag', [\n ['boolean', 'enableStatus', null, 'enabledStatus'],\n ['boolean', 'enableMove', null, 'enabledMove'],\n ['number', 'dragDelay', 0, null, 0],\n ['boolean', 'enableCollapse', null, 'enabledCollapse'],\n [\n 'boolean', 'enableHotkey', null, 'enabledHotkey', null, function (isHotkey) {\n if (isHotkey) {\n $scope.enabledMove = false;\n } else {\n $scope.enabledMove = $scope.statusMove;\n }\n }]\n ]],\n [\n ['enableDrag', 'enableStatus'], [\n [\n 'string', 'templateCopy', $attrs.templateCopy, 'templateCopy', null,\n function (_url) {\n if (_url && $templateCache.get(_url)) {\n $TreeDnDTemplate.setCopy(_url, $scope);\n }\n }],\n [\n 'string', 'templateMove', $attrs.templateMove, 'templateMove', null,\n function (_url) {\n if (_url && $templateCache.get(_url)) {\n $TreeDnDTemplate.setMove(_url, $scope);\n }\n }]\n ]],\n [\n [['enableDrag', 'enableDrop']], [\n ['number', 'dragBorder', 30, 'dragBorder', 30]]\n ],\n [\n '*', [\n ['boolean', 'treeTable', true, 'treeTable', null],\n ['boolean', 'horizontal'],\n [\n 'callback', 'treeClass', function (val) {\n switch (typeof val) {\n case 'string':\n $scope.$tree_class = val;\n break;\n case 'object':\n angular.extend($scope.$class, val);\n $scope.$tree_class = $scope.$class.tree;\n break;\n default:\n $scope.$tree_class = $attrs.treeClass;\n break;\n }\n }, 'treeClass', function () {\n $scope.$tree_class = $scope.$class.tree + ' table';\n }, null, function () {\n if (/^(\\s+[\\w\\-]+){2,}$/g.test(' ' + $attrs.treeClass)) {\n $scope.$tree_class = $attrs.treeClass.trim();\n return true;\n }\n }],\n [\n ['object', 'string'], 'expandOn', getExpandOn, 'expandingProperty', getExpandOn,\n function (expandOn) {\n if (angular.isUndefinedOrNull(expandOn)) {\n $scope.expandingProperty = $attrs.expandOn;\n }\n }],\n [\n 'object', 'treeControl', angular.isDefined($scope.tree) ? $scope.tree : {},\n 'tree', null, function ($tree) {\n\n if (!angular.isFunction(_fnGetControl)) {\n _fnGetControl = $TreeDnDPlugin('$TreeDnDControl');\n }\n\n if (angular.isFunction(_fnGetControl)) {\n tree = angular.extend(\n $tree,\n _fnGetControl($scope)\n );\n }\n }],\n [\n ['array', 'object'], 'columnDefs', getColDefs, 'colDefinitions', getColDefs,\n function (colDefs) {\n if (angular.isUndefinedOrNull(colDefs) || !angular.isArray(colDefs)) {\n $scope.colDefinitions = getColDefs();\n }\n }],\n [['object', 'string', 'array', 'function'], 'orderBy', $attrs.orderBy],\n [\n ['object', 'array'], 'filter', null, 'filter', null, function (filters) {\n var _passed = false;\n if (angular.isDefined(filters) && !angular.isArray(filters)) {\n var _keysF = Object.keys(filters),\n _lenF = _keysF.length, _iF;\n\n if (_lenF > 0) {\n for (_iF = 0; _iF < _lenF; _iF++) {\n\n if (typeof filters[_keysF[_iF]] === 'string' &&\n filters[_keysF[_iF]].length === 0) {\n continue;\n }\n _passed = true;\n break;\n }\n }\n }\n\n $scope.enabledFilter = _passed;\n reload_data();\n }],\n [\n 'object', 'filterOptions', _defaultFilterOption, 'filterOptions',\n _defaultFilterOption, function (option) {\n if (typeof option === 'object') {\n $scope.filterOptions = angular.extend(_defaultFilterOption, option);\n }\n }],\n ['string', 'primaryKey', $attrs.primaryKey, 'primary_key', '__uid__'],\n ['string', 'indentUnit', $attrs.indentUnit, 'indent_unit'],\n ['number', 'indent', 30, null, 30],\n ['number', 'indentPlus', 20, null, 20],\n [\n 'null', 'callbacks',\n function (optCallbacks) {\n angular.forEach(\n optCallbacks, function (value, key) {\n if (typeof value === 'function') {\n if ($scope.$callbacks[key]) {\n $scope.$callbacks[key] = value;\n }\n }\n }\n );\n return $scope.$callbacks;\n },\n '$callbacks'\n ],\n [\n 'number', 'expandLevel', 3, 'expandLevel', 3, function () {\n reload_data();\n }],\n ['number', 'treeLimit', 100, '$TreeLimit', 100],\n ['boolean', 'enableDrag', null, 'dragEnabled'],\n ['boolean', 'enableDrop', null, 'dropEnabled']\n ]]\n ],\n w, lenW = _watches.length,\n i, len,\n _curW,\n _typeW, _nameW, _defaultW, _scopeW, _NotW, _AfterW, _BeforeW,\n\n // debounce reload_Data;\n timeReloadData, tmpTreeData;\n\n for (w = 0; w < lenW; w++) {\n // skip if not exist\n if (!check_exist_attr($attrs, _watches[w][0], true)) {\n continue;\n }\n _curW = _watches[w][1];\n for (i = 0, len = _curW.length; i < len; i++) {\n _typeW = _curW[i][0];\n _nameW = _curW[i][1];\n _defaultW = _curW[i][2];\n _scopeW = _curW[i][3];\n _NotW = _curW[i][4];\n _AfterW = _curW[i][5];\n _BeforeW = _curW[i][6];\n generateWatch(_typeW, _nameW, _defaultW, _scopeW, _NotW, _AfterW, _BeforeW);\n }\n }\n\n if ($attrs.treeData) {\n $scope.$watch(\n $attrs.treeData, function (val) {\n if (angular.equals(val, $scope.treeData)) {\n return;\n }\n\n tmpTreeData = val;\n if (angular.isUndefinedOrNull(timeReloadData)) {\n timeReloadData = $timeout(timeLoadData, 350);\n }\n }, true\n );\n }\n\n function timeLoadData() {\n $scope.treeData = tmpTreeData;\n reload_data();\n timeReloadData = null;\n }\n\n $scope.updateLimit = function updateLimit() {\n //console.log('Call fn UpdateLimit');\n $scope.$TreeLimit += 50;\n };\n\n $scope.reload_data = reload_data;\n\n function check_exist_attr(attrs, existAttr, isAnd) {\n if (angular.isUndefinedOrNull(existAttr)) {\n return false;\n }\n\n if (existAttr === '*' || !angular.isUndefined(attrs[existAttr])) {\n return true;\n }\n\n if (angular.isArray(existAttr)) {\n return for_each_attrs(attrs, existAttr, isAnd);\n }\n }\n\n function for_each_attrs(attrs, exist, isAnd) {\n var i, len = exist.length, passed = false;\n\n if (len === 0) {\n return null;\n }\n for (i = 0; i < len; i++) {\n if (check_exist_attr(attrs, exist[i], !isAnd)) {\n passed = true;\n if (!isAnd) {\n return true;\n }\n } else {\n if (isAnd) {\n return false;\n }\n }\n }\n\n return passed;\n }\n\n function generateWatch(type, nameAttr, valDefault, nameScope, fnNotExist, fnAfter,\n fnBefore\n ) {\n nameScope = nameScope || nameAttr;\n if (typeof type === 'string' || angular.isArray(type)) {\n if (angular.isFunction(fnBefore) && fnBefore()) {\n return;//jmp\n }\n if (typeof $attrs[nameAttr] === 'string') {\n $scope.$watch(\n $attrs[nameAttr], function (val) {\n if (typeof type === 'string' && typeof val === type ||\n angular.isArray(type) && type.indexOf(typeof val) > -1\n ) {\n $scope[nameScope] = val;\n } else {\n if (angular.isFunction(valDefault)) {\n $scope[nameScope] = valDefault(val);\n } else {\n $scope[nameScope] = valDefault;\n }\n }\n\n if (angular.isFunction(fnAfter)) {\n fnAfter($scope[nameScope], $scope);\n }\n }, true\n );\n } else {\n\n if (angular.isFunction(fnNotExist)) {\n $scope[nameScope] = fnNotExist();\n } else if (!angular.isUndefined(fnNotExist)) {\n $scope[nameScope] = fnNotExist;\n }\n }\n }\n }\n\n function $safeApply(fn) {\n var phase = this.$root.$$phase;\n if (phase === '$apply' || phase === '$digest') {\n if (fn && typeof fn === 'function') {\n fn();\n }\n } else {\n this.$apply(fn);\n }\n }\n\n function getExpandOn() {\n if ($scope.treeData && $scope.treeData.length) {\n var _firstNode = $scope.treeData[0], _keys = Object.keys(_firstNode),\n _regex = new RegExp('^__([a-zA-Z0-9_\\-]*)__$'),\n _len,\n i;\n // Auto get first field with type is string;\n for (i = 0, _len = _keys.length; i < _len; i++) {\n if (typeof _firstNode[_keys[i]] === 'string' && !_regex.test(_keys[i])) {\n $scope.expandingProperty = _keys[i];\n return;\n }\n }\n\n // Auto get first\n if (angular.isUndefinedOrNull($scope.expandingProperty)) {\n $scope.expandingProperty = _keys[0];\n }\n\n }\n }\n\n function getColDefs() {\n // Auto get Defs except attribute __level__ ....\n if ($scope.treeData.length) {\n var _col_defs = [], _firstNode = $scope.treeData[0],\n _regex = new RegExp('(^__([a-zA-Z0-9_\\-]*)__$|^' + $scope.expandingProperty + '$)'),\n _keys = Object.keys(_firstNode),\n i, _len;\n // Auto get first field with type is string;\n for (i = 0, _len = _keys.length; i < _len; i++) {\n if (typeof _firstNode[_keys[i]] === 'string' && !_regex.test(_keys[i])) {\n _col_defs.push(\n {\n field: _keys[i]\n }\n );\n }\n }\n $scope.colDefinitions = _col_defs;\n }\n }\n\n function do_f(root, node, parent, parent_real, level, visible, index) {\n\n if(typeof node !== 'object'){\n return 0;\n }\n\n var _i, _len, _icon, _index_real, _dept, _hashKey;\n if (!angular.isArray(node.__children__)) {\n node.__children__ = [];\n }\n\n node.__parent_real__ = parent_real;\n node.__parent__ = parent;\n _len = node.__children__.length;\n\n if (angular.isUndefinedOrNull(node.__expanded__) && _len > 0) {\n node.__expanded__ = level < $scope.expandLevel;\n }\n\n if (_len === 0) {\n _icon = -1;\n } else {\n if (node.__expanded__) {\n _icon = 1;\n } else {\n _icon = 0;\n }\n }\n\n // Insert item vertically\n _index_real = root.length;\n node.__index__ = index;\n node.__index_real__ = _index_real;\n node.__level__ = level;\n node.__icon__ = _icon;\n node.__icon_class__ = $scope.$class.icon[_icon];\n node.__visible__ = !!visible;\n\n if (angular.isUndefinedOrNull(node.__uid__)) {\n node.__uid__ = '' + Math.random();\n }\n\n _hashKey = $scope.getHash(node);\n\n if (angular.isUndefinedOrNull(node.__hashKey__) || node.__hashKey__ !== _hashKey) {\n node.__hashKey__ = _hashKey;\n }\n\n root.push(node);\n\n // Check node children\n _dept = 1;\n if (_len > 0) {\n for (_i = 0; _i < _len; _i++) {\n _dept += do_f(\n root,\n node.__children__[_i],\n node[$scope.primary_key],\n _index_real,\n level + 1,\n visible && node.__expanded__,\n _i\n );\n }\n }\n\n node.__dept__ = _dept;\n\n return _dept;\n }\n\n function init_data(data) {\n\n // clear memory\n if (angular.isDefined($scope.tree_nodes)) {\n delete $scope.tree_nodes;\n }\n\n $scope.tree_nodes = data;\n return data;\n }\n\n function reload_data(oData) {\n var _data,\n _len,\n _tree_nodes = [];\n if (angular.isDefined(oData)) {\n if (!angular.isArray(oData) || oData.length === 0) {\n return init_data([]);\n } else {\n _data = oData;\n }\n } else if (!angular.isArray($scope.treeData) || $scope.treeData.length === 0) {\n return init_data([]);\n } else {\n _data = $scope.treeData;\n }\n\n if (!$attrs.expandOn) {\n getExpandOn();\n }\n\n if (!$attrs.columnDefs) {\n getColDefs();\n }\n\n if (angular.isDefined($scope.orderBy)) {\n if (!angular.isFunction(_fnInitOrderBy)) {\n _fnInitOrderBy = $TreeDnDPlugin('$TreeDnDOrderBy');\n }\n\n if (angular.isFunction(_fnInitOrderBy)) {\n _data = _fnInitOrderBy(_data, $scope.orderBy);\n }\n }\n\n if (angular.isDefined($scope.filter)) {\n if (!angular.isFunction(_fnInitFilter)) {\n _fnInitFilter = $TreeDnDPlugin('$TreeDnDFilter');\n }\n\n if (angular.isFunction(_fnInitFilter)) {\n _data = _fnInitFilter(_data, $scope.filter, $scope.filterOptions);\n }\n }\n\n _len = _data.length;\n if (_len > 0) {\n var _i,\n _deptTotal = 0;\n\n for (_i = 0; _i < _len; _i++) {\n _deptTotal += do_f(_tree_nodes, _data[_i], null, null, 1, true, _i);\n }\n\n }\n\n init_data(_tree_nodes);\n\n return _tree_nodes;\n }\n }\n\n function fnCompile(tElement) {\n\n var $_Template = '',\n _element = tElement.html().trim();\n\n if (_element.length > 0) {\n $_Template = _element;\n tElement.html('');\n }\n\n return function fnPost(scope, element, attrs) {\n\n if (attrs.enableDrag) {\n var _fnInitDrag = $TreeDnDPlugin('$TreeDnDDrag');\n if (angular.isFunction(_fnInitDrag)) {\n _fnInitDrag(scope, element, $window, $document);\n }\n }\n\n // kick out $digest\n element.ready(function () {\n // apply Template\n function checkTreeTable(template, scope) {\n var elemNode = template[0].querySelector('[tree-dnd-node]'),\n attrInclude;\n\n scope.isTable = null;\n if (elemNode) {\n elemNode = angular.element(elemNode);\n attrInclude = elemNode.attr('ng-include');\n } else {\n return;\n }\n\n if (attrInclude) {\n var treeInclude = $parse(attrInclude)(scope) || attrInclude;\n if (typeof treeInclude === 'string') {\n return $http.get(\n treeInclude,\n {cache: $templateCache}\n ).success(\n function (data) {\n data = data.trim();\n //scope.templateNode = data;\n var tempDiv = document.createElement('div');\n tempDiv.innerHTML = data;\n tempDiv = angular.element(tempDiv);\n scope.isTable = !tempDiv[0].querySelector('[tree-dnd-nodes]');\n }\n );\n }\n } else {\n scope.isTable = !elemNode[0].querySelector('[tree-dnd-nodes]');\n //scope.templateNode = elemNode.html();\n }\n $TreeDnDViewport.setTemplate(scope, scope.templateNode);\n //elemNode.html('');\n }\n\n //scope.$watch(tableDataLoaded, transformTable);\n /*\n function tableDataLoaded(elem) {\n // first cell in the tbody exists when data is loaded but doesn't have a width\n // until after the table is transformed\n var firstCell = elem.querySelector('tbody tr:first-child td:first-child');\n return firstCell && !firstCell.style.width;\n }\n\n function transformTable(elem, attrs) {\n // reset display styles so column widths are correct when measured below\n angular.element(elem.querySelectorAll('thead, tbody, tfoot')).css('display', '');\n\n // wrap in $timeout to give table a chance to finish rendering\n $timeout(function () {\n // set widths of columns\n angular.forEach(elem.querySelectorAll('tr:first-child th'), function (thElem, i) {\n\n var tdElems = elem.querySelector('tbody tr:first-child td:nth-child(' + (i + 1) + ')');\n var tfElems = elem.querySelector('tfoot tr:first-child td:nth-child(' + (i + 1) + ')');\n\n var columnWidth = tdElems ? tdElems.offsetWidth : thElem.offsetWidth;\n if (tdElems) {\n tdElems.style.width = columnWidth + 'px';\n }\n if (thElem) {\n thElem.style.width = columnWidth + 'px';\n }\n if (tfElems) {\n tfElems.style.width = columnWidth + 'px';\n }\n });\n\n // set css styles on thead and tbody\n angular.element(elem.querySelectorAll('thead, tfoot')).css('display', 'block');\n\n angular.element(elem.querySelectorAll('tbody')).css({\n 'display': 'block',\n 'height': attrs.tableHeight || 'inherit',\n 'overflow': 'auto'\n });\n\n // reduce width of last column by width of scrollbar\n var tbody = elem.querySelector('tbody');\n var scrollBarWidth = tbody.offsetWidth - tbody.clientWidth;\n if (scrollBarWidth > 0) {\n // for some reason trimming the width by 2px lines everything up better\n scrollBarWidth -= 2;\n var lastColumn = elem.querySelector('tbody tr:first-child td:last-child');\n lastColumn.style.width = lastColumn.offsetWidth - scrollBarWidth + 'px';\n }\n });\n }*/\n var promiseCheck;\n if ($_Template.length > 0) {\n promiseCheck = checkTreeTable(angular.element($_Template.trim()), scope);\n if (typeof promiseCheck === 'object') {\n promiseCheck.then(function () {\n element.append($compile($_Template)(scope));\n });\n } else {\n element.append($compile($_Template)(scope));\n }\n } else {\n $http.get(\n attrs.templateUrl || $TreeDnDTemplate.getPath(),\n {cache: $templateCache}\n ).success(\n function (data) {\n data = angular.element(data.trim());\n promiseCheck = checkTreeTable(data, scope);\n if (typeof promiseCheck === 'object') {\n promiseCheck.then(function () {\n element.append($compile(data)(scope));\n });\n } else {\n element.append($compile(data)(scope));\n }\n }\n );\n }\n })\n };\n }\n}\n\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDFilter', [\n '$filter', function ($filter) {\n return fnInitFilter;\n\n function for_all_descendants(options, node, fieldChild, fnBefore, fnAfter, parentPassed) {\n if (!angular.isFunction(fnBefore)) {\n return null;\n }\n\n var _i, _len, _nodes,\n _nodePassed = fnBefore(options, node),\n _childPassed = false,\n _filter_index = options.filter_index;\n\n if (angular.isDefined(node[fieldChild])) {\n _nodes = node[fieldChild];\n _len = _nodes.length;\n options.filter_index = 0;\n for (_i = 0; _i < _len; _i++) {\n _childPassed = for_all_descendants(\n options,\n _nodes[_i],\n fieldChild,\n fnBefore,\n fnAfter,\n _nodePassed || parentPassed\n ) || _childPassed;\n }\n\n // restore filter_index of node\n options.filter_index = _filter_index;\n }\n\n if (angular.isFunction(fnAfter)) {\n fnAfter(options, node, _nodePassed === true, _childPassed === true, parentPassed === true);\n }\n\n return _nodePassed || _childPassed;\n }\n\n /**\n * Check data with callback\n * @param {string|object|function|regex} callback\n * @param {*} data\n * @returns {null|boolean}\n * @private\n */\n function _fnCheck(callback, data) {\n if (angular.isUndefinedOrNull(data) || angular.isArray(data)) {\n return null;\n }\n\n if (angular.isFunction(callback)) {\n return callback(data, $filter);\n } else {\n if (typeof callback === 'boolean') {\n data = !!data;\n return data === callback;\n } else if (angular.isDefined(callback)) {\n try {\n var _regex = new RegExp(callback);\n return _regex.test(data);\n }\n catch (err) {\n if (typeof data === 'string') {\n return data.indexOf(callback) > -1;\n } else {\n return null;\n }\n }\n } else {\n return null;\n }\n }\n }\n\n /**\n * `fnProcess` to call `_fnCheck`. If `condition` is `array` then call `for_each_filter`\n * else will call `_fnCheck`. Specical `condition.field` is `_$` then apply `condition.callback` for all field, if have `field` invaild then `return true`.\n *\n * @param node\n * @param condition\n * @param isAnd\n * @returns {null|boolean}\n * @private\n */\n function _fnProccess(node, condition, isAnd) {\n if (angular.isArray(condition)) {\n return for_each_filter(node, condition, isAnd);\n } else {\n var _key = condition.field,\n _callback = condition.callback,\n _iO, _keysO, _lenO;\n\n if (_key === '_$') {\n _keysO = Object.keys(node);\n _lenO = _keysO.length;\n for (_iO = 0; _iO < _lenO; _iO++) {\n if (_fnCheck(_callback, node[_keysO[_iO]])) {\n return true;\n }\n }\n } else if (angular.isDefined(node[_key])) {\n return _fnCheck(_callback, node[_key]);\n }\n }\n return null;\n }\n\n /**\n *\n * @param {object} node\n * @param {array} conditions Array `conditions`\n * @param {boolean} isAnd check with condition `And`, if `And` then `return false` when all `false`\n * @returns {null|boolean}\n */\n function for_each_filter(node, conditions, isAnd) {\n var i, len = conditions.length || 0, passed = false;\n if (len === 0) {\n return null;\n }\n\n for (i = 0; i < len; i++) {\n if (_fnProccess(node, conditions[i], !isAnd)) {\n passed = true;\n // if condition `or` then return;\n if (!isAnd) {\n return true;\n }\n } else {\n\n // if condition `and` and result in fnProccess = false then return;\n if (isAnd) {\n return false;\n }\n }\n }\n\n return passed;\n }\n\n /**\n * Will call _fnAfter to clear data no need\n * @param {object} options\n * @param {object} node\n * @param {boolean} isNodePassed\n * @param {boolean} isChildPassed\n * @param {boolean} isParentPassed\n * @private\n */\n function _fnAfter(options, node, isNodePassed, isChildPassed, isParentPassed) {\n if (isNodePassed === true) {\n node.__filtered__ = true;\n node.__filtered_visible__ = true;\n node.__filtered_index__ = options.filter_index++;\n return; //jmp\n } else if (isChildPassed === true && options.showParent === true\n || isParentPassed === true && options.showChild === true) {\n node.__filtered__ = false;\n node.__filtered_visible__ = true;\n node.__filtered_index__ = options.filter_index++;\n return; //jmp\n }\n\n // remove attr __filtered__\n delete node.__filtered__;\n delete node.__filtered_visible__;\n delete node.__filtered_index__;\n }\n\n /**\n * `fnBefore` will called when `for_all_descendants` of `node` checking.\n * If `filter` empty then return `true` else result of function `_fnProccess` {@see _fnProccess}\n *\n * @param {object} options\n * @param {object} node\n * @returns {null|boolean}\n * @private\n */\n function _fnBefore(options, node) {\n if (options.filter.length === 0) {\n return true;\n } else {\n return _fnProccess(node, options.filter, options.beginAnd || false);\n }\n }\n\n /**\n * `fnBeforeClear` will called when `for_all_descendants` of `node` checking.\n * Alway false to Clear Filter empty\n *\n * @param {object} options\n * @param {object} node\n * @returns {null|boolean}\n * @private\n */\n function _fnBeforeClear(options, node) {\n return false;\n }\n\n /**\n * `_fnConvert` to convert `filter` `object` to `array` invaild.\n *\n * @param {object|array} filters\n * @returns {array} Instead of `filter` or new array invaild *(converted from filter)*\n * @private\n */\n function _fnConvert(filters) {\n var _iF, _lenF, _keysF,\n _filter,\n _state;\n // convert filter object to array filter\n if (angular.isObject(filters) && !angular.isArray(filters)) {\n _keysF = Object.keys(filters);\n _lenF = _keysF.length;\n _filter = [];\n\n if (_lenF > 0) {\n for (_iF = 0; _iF < _lenF; _iF++) {\n\n if (typeof filters[_keysF[_iF]] === 'string' && filters[_keysF[_iF]].length === 0) {\n continue;\n } else if (angular.isArray(filters[_keysF[_iF]])) {\n _state = filters[_keysF[_iF]];\n } else if (angular.isObject(filters[_keysF[_iF]])) {\n _state = _fnConvert(filters[_keysF[_iF]]);\n } else {\n _state = {\n field: _keysF[_iF],\n callback: filters[_keysF[_iF]]\n };\n }\n _filter.push(_state);\n }\n }\n _state = null;\n return _filter;\n }\n else {\n return filters;\n }\n }\n\n /**\n * `fnInitFilter` function is constructor of service `$TreeDnDFilter`.\n * @constructor\n * @param {object|array} treeData\n * @param {object|array} filters\n * @param {object} options\n * @param {string} keyChild\n * @returns {array} Return `treeData` or `treeData` with `filter`\n * @private\n */\n function fnInitFilter(treeData, filters, options, keyChild) {\n if (!angular.isArray(treeData)\n || treeData.length === 0) {\n return treeData;\n }\n\n var _i, _len,\n _filter;\n\n _filter = _fnConvert(filters);\n if (!(angular.isArray(_filter) || angular.isObject(_filter))\n || _filter.length === 0) {\n for (_i = 0, _len = treeData.length; _i < _len; _i++) {\n for_all_descendants(\n options,\n treeData[_i],\n keyChild || '__children__',\n _fnBeforeClear, _fnAfter\n );\n }\n return treeData;\n }\n\n options.filter = _filter;\n options.filter_index = 0;\n for (_i = 0, _len = treeData.length; _i < _len; _i++) {\n for_all_descendants(\n options,\n treeData[_i],\n keyChild || '__children__',\n _fnBefore, _fnAfter\n );\n }\n\n return treeData;\n }\n\n }]\n);\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDOrderBy', [\n '$filter', function ($filter) {\n var _fnOrderBy = $filter('orderBy'),\n for_all_descendants = function for_all_descendants(options, node, name, fnOrderBy) {\n var _i, _len, _nodes;\n\n if (angular.isDefined(node[name])) {\n _nodes = node[name];\n _len = _nodes.length;\n // OrderBy children\n for (_i = 0; _i < _len; _i++) {\n _nodes[_i] = for_all_descendants(options, _nodes[_i], name, fnOrderBy);\n }\n\n node[name] = fnOrderBy(node[name], options);\n }\n return node;\n },\n _fnOrder = function _fnOrder(list, orderBy) {\n return _fnOrderBy(list, orderBy);\n },\n _fnMain = function _fnMain(treeData, orderBy) {\n if (!angular.isArray(treeData)\n || treeData.length === 0\n || !(angular.isArray(orderBy) || angular.isObject(orderBy) || angular.isString(orderBy) || angular.isFunction(orderBy))\n || orderBy.length === 0 && !angular.isFunction(orderBy)) {\n return treeData;\n }\n\n var _i, _len;\n\n for (_i = 0, _len = treeData.length; _i < _len; _i++) {\n treeData[_i] = for_all_descendants(\n orderBy,\n treeData[_i],\n '__children__',\n _fnOrder\n );\n }\n\n return _fnOrder(treeData, orderBy);\n };\n\n return _fnMain;\n }]\n);\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDConvert', function () {\n var _$initConvert = {\n line2tree: function (data, primaryKey, parentKey, callback) {\n callback = typeof callback === 'function' ? callback : function () {\n };\n if (!data || data.length === 0 || !primaryKey || !parentKey) {\n return [];\n }\n var tree = [],\n rootIds = [],\n item = data[0],\n _primary = item[primaryKey],\n treeObjs = {},\n parentId, parent,\n len = data.length,\n i = 0;\n while (i < len) {\n item = data[i++];\n callback(item);\n _primary = item[primaryKey];\n treeObjs[_primary] = item;\n }\n i = 0;\n while (i < len) {\n item = data[i++];\n callback(item);\n _primary = item[primaryKey];\n treeObjs[_primary] = item;\n parentId = item[parentKey];\n if (parentId) {\n parent = treeObjs[parentId];\n if (parent) {\n if (parent.__children__) {\n parent.__children__.push(item);\n } else {\n parent.__children__ = [item];\n }\n }\n } else {\n rootIds.push(_primary);\n }\n }\n len = rootIds.length;\n for (i = 0; i < len; i++) {\n tree.push(treeObjs[rootIds[i]]);\n }\n return tree;\n },\n tree2tree: function access_child(data, containKey, callback) {\n callback = typeof callback === 'function' ? callback : function () {\n };\n var _tree = [],\n _i,\n _len = data ? data.length : 0,\n _copy, _child;\n for (_i = 0; _i < _len; _i++) {\n _copy = angular.copy(data[_i]);\n callback(_copy);\n if (angular.isArray(_copy[containKey]) && _copy[containKey].length > 0) {\n _child = access_child(_copy[containKey], containKey, callback);\n delete _copy[containKey];\n _copy.__children__ = _child;\n }\n _tree.push(_copy);\n }\n return _tree;\n }\n };\n\n return _$initConvert;\n }\n );\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDHelper', [\n '$document', '$window', function ($document, $window) {\n var _$helper = {\n nodrag: function (targetElm) {\n return typeof targetElm.attr('data-nodrag') !== 'undefined';\n },\n eventObj: function (e) {\n var obj = e;\n if (e.targetTouches !== undefined) {\n obj = e.targetTouches.item(0);\n } else if (e.originalEvent !== undefined && e.originalEvent.targetTouches !== undefined) {\n obj = e.originalEvent.targetTouches.item(0);\n }\n return obj;\n },\n dragInfo: function (scope) {\n var _node = scope.getData(),\n _tree = scope.getScopeTree(),\n _parent = scope.getNode(_node.__parent_real__);\n return {\n node: _node,\n parent: _parent,\n move: {\n parent: _parent,\n pos: _node.__index__\n },\n scope: scope,\n target: _tree,\n drag: _tree,\n drop: scope.getPrevSibling(_node),\n changed: false\n };\n },\n height: function (element) {\n return element.prop('scrollHeight');\n },\n width: function (element) {\n return element.prop('scrollWidth');\n },\n offset: function (element) {\n var boundingClientRect = element[0].getBoundingClientRect();\n return {\n width: element.prop('offsetWidth'),\n height: element.prop('offsetHeight'),\n top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop),\n left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft)\n };\n },\n positionStarted: function (e, target) {\n var pos = {};\n pos.offsetX = e.pageX - this.offset(target).left;\n pos.offsetY = e.pageY - this.offset(target).top;\n pos.startX = pos.lastX = e.pageX;\n pos.startY = pos.lastY = e.pageY;\n pos.nowX = pos.nowY = pos.distX = pos.distY = pos.dirAx = 0;\n pos.dirX = pos.dirY = pos.lastDirX = pos.lastDirY = pos.distAxX = pos.distAxY = 0;\n return pos;\n },\n positionMoved: function (e, pos, firstMoving) {\n // mouse position last events\n pos.lastX = pos.nowX;\n pos.lastY = pos.nowY;\n // mouse position this events\n pos.nowX = e.pageX;\n pos.nowY = e.pageY;\n // distance mouse moved between events\n pos.distX = pos.nowX - pos.lastX;\n pos.distY = pos.nowY - pos.lastY;\n // direction mouse was moving\n pos.lastDirX = pos.dirX;\n pos.lastDirY = pos.dirY;\n // direction mouse is now moving (on both axis)\n pos.dirX = pos.distX === 0 ? 0 : pos.distX > 0 ? 1 : -1;\n pos.dirY = pos.distY === 0 ? 0 : pos.distY > 0 ? 1 : -1;\n // axis mouse is now moving on\n var newAx = Math.abs(pos.distX) > Math.abs(pos.distY) ? 1 : 0;\n // do nothing on first move\n if (firstMoving) {\n pos.dirAx = newAx;\n pos.moving = true;\n return;\n }\n // calc distance moved on this axis (and direction)\n if (pos.dirAx !== newAx) {\n pos.distAxX = 0;\n pos.distAxY = 0;\n } else {\n pos.distAxX += Math.abs(pos.distX);\n if (pos.dirX !== 0 && pos.dirX !== pos.lastDirX) {\n pos.distAxX = 0;\n }\n pos.distAxY += Math.abs(pos.distY);\n if (pos.dirY !== 0 && pos.dirY !== pos.lastDirY) {\n pos.distAxY = 0;\n }\n }\n pos.dirAx = newAx;\n },\n replaceIndent: function (scope, element, indent, attr) {\n attr = attr || 'left';\n angular.element(element.children()[0]).css(attr, scope.$callbacks.calsIndent(indent));\n }\n };\n return _$helper;\n }]\n );\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDPlugin', ['$injector', function ($injector) {\n var _fnget = function (name) {\n if (angular.isDefined($injector) && $injector.has(name)) {\n return $injector.get(name);\n }\n return null;\n };\n return _fnget;\n }]\n );\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDTemplate', [\n '$templateCache', function ($templateCache) {\n var templatePath = 'template/TreeDnD/TreeDnD.html',\n copyPath = 'template/TreeDnD/TreeDnDStatusCopy.html',\n movePath = 'template/TreeDnD/TreeDnDStatusMove.html',\n scopes = {},\n temp,\n _$init = {\n setMove: function (path, scope) {\n if (!scopes[scope.$id]) {\n scopes[scope.$id] = {};\n }\n scopes[scope.$id].movePath = path;\n },\n setCopy: function (path, scope) {\n if (!scopes[scope.$id]) {\n scopes[scope.$id] = {};\n }\n scopes[scope.$id].copyPath = path;\n },\n getPath: function () {\n return templatePath;\n },\n getCopy: function (scope) {\n if (scopes[scope.$id] && scopes[scope.$id].copyPath) {\n temp = $templateCache.get(scopes[scope.$id].copyPath);\n if (temp) {\n return temp;\n }\n }\n return $templateCache.get(copyPath);\n },\n getMove: function (scope) {\n if (scopes[scope.$id] && scopes[scope.$id].movePath) {\n temp = $templateCache.get(scopes[scope.$id].movePath);\n if (temp) {\n return temp;\n }\n }\n return $templateCache.get(movePath);\n }\n };\n\n return _$init;\n }]\n );\n\nangular.module('ntt.TreeDnD')\n .factory('$TreeDnDViewport', fnInitTreeDnDViewport);\n\nfnInitTreeDnDViewport.$inject = ['$window', '$document', '$timeout', '$q', '$compile'];\n\nfunction fnInitTreeDnDViewport($window, $document, $timeout, $q, $compile) {\n\n var viewport = null,\n isUpdating = false,\n isRender = false,\n updateAgain = false,\n viewportRect,\n items = [],\n nodeTemplate,\n updateTimeout,\n renderTime,\n $initViewport = {\n setViewport: setViewport,\n getViewport: getViewport,\n add: add,\n setTemplate: setTemplate,\n getItems: getItems,\n updateDelayed: updateDelayed\n },\n eWindow = angular.element($window);\n\n eWindow.on('load resize scroll', updateDelayed);\n\n return $initViewport;\n\n function update() {\n\n viewportRect = {\n width: eWindow.prop('offsetWidth') || document.documentElement.clientWidth,\n height: eWindow.prop('offsetHeight') || document.documentElement.clientHeight,\n top: $document[0].body.scrollTop || $document[0].documentElement.scrollTop,\n left: $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft\n };\n\n if (isUpdating || isRender) {\n updateAgain = true;\n return;\n }\n isUpdating = true;\n\n recursivePromise();\n }\n\n function recursivePromise() {\n if (isRender) {\n return;\n }\n\n var number = number > 0 ? number : items.length, item;\n\n if (number > 0) {\n item = items[0];\n\n isRender = true;\n renderTime = $timeout(function () {\n //item.element.html(nodeTemplate);\n //$compile(item.element.contents())(item.scope);\n\n items.splice(0, 1);\n isRender = false;\n number--;\n $timeout.cancel(renderTime);\n recursivePromise();\n }, 0);\n\n } else {\n isUpdating = false;\n if (updateAgain) {\n updateAgain = false;\n update();\n }\n }\n\n }\n\n /**\n * Check if a point is inside specified bounds\n * @param x\n * @param y\n * @param bounds\n * @returns {boolean}\n */\n function pointIsInsideBounds(x, y, bounds) {\n return x >= bounds.left &&\n y >= bounds.top &&\n x <= bounds.left + bounds.width &&\n y <= bounds.top + bounds.height;\n }\n\n /**\n * @name setViewport\n * @desciption Set the viewport element\n * @param element\n */\n function setViewport(element) {\n viewport = element;\n }\n\n /**\n * Return the current viewport\n * @returns {*}\n */\n function getViewport() {\n return viewport;\n }\n\n /**\n * trigger an update\n */\n function updateDelayed() {\n $timeout.cancel(updateTimeout);\n updateTimeout = $timeout(function () {\n update();\n }, 0);\n }\n\n /**\n * Add listener for event\n * @param element\n * @param callback\n */\n function add(scope, element) {\n updateDelayed();\n items.push({\n element: element,\n scope: scope\n });\n }\n\n function setTemplate(scope, template) {\n nodeTemplate = template;\n }\n\n /**\n * Get list of items\n * @returns {Array}\n */\n function getItems() {\n return items;\n }\n}\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDDrag', [\n '$timeout', '$TreeDnDHelper',\n function ($timeout, $TreeDnDHelper) {\n function _fnPlaceHolder(e, $params) {\n if ($params.placeElm) {\n var _offset = $TreeDnDHelper.offset($params.placeElm);\n if (_offset.top <= e.pageY && e.pageY <= _offset.top + _offset.height &&\n _offset.left <= e.pageX && e.pageX <= _offset.left + _offset.width\n ) {\n return true;\n }\n }\n return false;\n }\n\n function _fnDragStart(e, $params) {\n if (!$params.hasTouch && (e.button === 2 || e.which === 3)) {\n // disable right click\n return;\n }\n if (e.uiTreeDragging || e.originalEvent && e.originalEvent.uiTreeDragging) { // event has already fired in other scope.\n return;\n }\n // the element which is clicked.\n var eventElm = angular.element(e.target),\n eventScope = eventElm.scope();\n if (!eventScope || !eventScope.$type) {\n return;\n }\n // if (eventScope.$type !== 'TreeDnDNode') { // Check if it is a node or a handle\n // return;\n // }\n\n if (eventScope.$type !== 'TreeDnDNodeHandle') { // If the node has a handle, then it should be clicked by the handle\n return;\n }\n\n var eventElmTagName = eventElm.prop('tagName').toLowerCase(),\n dragScope,\n _$scope = $params.$scope;\n if (eventElmTagName === 'input'\n || eventElmTagName === 'textarea'\n || eventElmTagName === 'button'\n || eventElmTagName === 'select') { // if it's a input or button, ignore it\n return;\n }\n // check if it or it's parents has a 'data-nodrag' attribute\n while (eventElm && eventElm[0] && eventElm[0] !== $params.element) {\n if ($TreeDnDHelper.nodrag(eventElm)) { // if the node mark as `nodrag`, DONOT drag it.\n return;\n }\n eventElm = eventElm.parent();\n }\n\n e.uiTreeDragging = true; // stop event bubbling\n if (e.originalEvent) {\n e.originalEvent.uiTreeDragging = true;\n }\n e.preventDefault();\n\n dragScope = eventScope.getScopeNode();\n\n $params.dragInfo = $TreeDnDHelper.dragInfo(dragScope);\n\n if (!_$scope.$callbacks.beforeDrag(dragScope, $params.dragInfo)) {\n return;\n }\n\n $params.firstMoving = true;\n _$scope.setDragging($params.dragInfo);\n\n var eventObj = $TreeDnDHelper.eventObj(e);\n $params.pos = $TreeDnDHelper.positionStarted(eventObj, dragScope.$element);\n\n if (dragScope.isTable) {\n $params.dragElm = angular.element($params.$window.document.createElement('table'))\n .addClass(_$scope.$class.tree)\n .addClass(_$scope.$class.drag)\n .addClass(_$scope.$tree_class);\n } else {\n $params.dragElm = angular.element($params.$window.document.createElement('ul'))\n .addClass(_$scope.$class.drag)\n .addClass('tree-dnd-nodes')\n .addClass(_$scope.$tree_class);\n }\n\n $params.dragElm.css(\n {\n 'width': $TreeDnDHelper.width(dragScope.$element) + 'px',\n 'z-index': 9995\n }\n );\n\n $params.offsetEdge = 0;\n var _width = $TreeDnDHelper.width(dragScope.$element),\n _scope = dragScope,\n _element = _scope.$element,\n _clone,\n _needCollapse = !!_$scope.enabledCollapse,\n _copied = false,\n _tbody,\n _frag;\n\n if (_scope.isTable) {\n $params.offsetEdge = $params.dragInfo.node.__level__ - 1;\n _tbody = angular.element(document.createElement('tbody'));\n _frag = angular.element(document.createDocumentFragment());\n\n _$scope.for_all_descendants(\n $params.dragInfo.node, function (_node, _parent) {\n _scope = _$scope.getScope(_node);\n _element = _scope && _scope.$element;\n if (_scope && _element) {\n if (!_copied) {\n _clone = _element.clone();\n\n $TreeDnDHelper.replaceIndent(\n _$scope,\n _clone,\n _node.__level__ - $params.offsetEdge,\n 'padding-left'\n );\n\n _frag.append(_clone);\n\n // skip all, just clone parent\n if (_needCollapse) {\n _copied = true;\n }\n\n // hide if have status Move;\n if (_$scope.enabledMove && _$scope.$class.hidden &&\n (!_parent || _node.__visible__ || _parent.__visible__ && _parent.__expanded__)) {\n _element.addClass(_$scope.$class.hidden);\n }\n }\n }\n // skip children of node not expand.\n return _copied || _node.__visible__ === false || _node.__expanded__ === false;\n\n }, null, !_needCollapse\n );\n _tbody.append(_frag);\n $params.dragElm.append(_tbody);\n } else {\n\n _clone = _element.clone();\n if (_needCollapse) {\n _clone[0].querySelector('[tree-dnd-nodes]').remove();\n }\n\n // hide if have status Move;\n $params.dragElm.append(_clone);\n if (_$scope.enabledMove && _$scope.$class.hidden) {\n _element.addClass(_$scope.$class.hidden);\n }\n }\n\n $params.dragElm.css(\n {\n 'left': eventObj.pageX - $params.pos.offsetX + _$scope.$callbacks.calsIndent(\n $params.offsetEdge + 1,\n true,\n true\n ) + 'px',\n 'top': eventObj.pageY - $params.pos.offsetY + 'px'\n }\n );\n // moving item with descendant\n $params.$document.find('body').append($params.dragElm);\n if (_$scope.$callbacks.droppable()) {\n $params.placeElm = _$scope.initPlace(dragScope.$element, $params.dragElm);\n\n if (dragScope.isTable) {\n $TreeDnDHelper.replaceIndent(_$scope, $params.placeElm, $params.dragInfo.node.__level__);\n }\n\n $params.placeElm.css('width', _width);\n }\n\n _$scope.showPlace();\n _$scope.targeting = true;\n\n if (_$scope.enabledStatus) {\n _$scope.refreshStatus();\n _$scope.setPositionStatus(e);\n }\n\n angular.element($params.$document).bind('touchend', $params.dragEndEvent);\n angular.element($params.$document).bind('touchcancel', $params.dragEndEvent);\n angular.element($params.$document).bind('touchmove', $params.dragMoveEvent);\n angular.element($params.$document).bind('mouseup', $params.dragEndEvent);\n angular.element($params.$document).bind('mousemove', $params.dragMoveEvent);\n angular.element($params.$document).bind('mouseleave', $params.dragCancelEvent);\n\n $params.document_height = Math.max(\n $params.body.scrollHeight,\n $params.body.offsetHeight,\n $params.html.clientHeight,\n $params.html.scrollHeight,\n $params.html.offsetHeight\n );\n\n $params.document_width = Math.max(\n $params.body.scrollWidth,\n $params.body.offsetWidth,\n $params.html.clientWidth,\n $params.html.scrollWidth,\n $params.html.offsetWidth\n );\n }\n\n function _fnDragMove(e, $params) {\n var _$scope = $params.$scope;\n if (!$params.dragStarted) {\n if (!$params.dragDelaying) {\n $params.dragStarted = true;\n _$scope.$safeApply(\n function () {\n _$scope.$callbacks.dragStart($params.dragInfo);\n }\n );\n }\n return;\n }\n\n if ($params.dragElm) {\n e.preventDefault();\n if ($params.$window.getSelection) {\n $params.$window.getSelection().removeAllRanges();\n } else if ($params.$window.document.selection) {\n $params.$window.document.selection.empty();\n }\n\n var eventObj = $TreeDnDHelper.eventObj(e),\n leftElmPos = eventObj.pageX - $params.pos.offsetX,\n topElmPos = eventObj.pageY - $params.pos.offsetY;\n\n //dragElm can't leave the screen on the left\n if (leftElmPos < 0) {\n leftElmPos = 0;\n }\n\n //dragElm can't leave the screen on the top\n if (topElmPos < 0) {\n topElmPos = 0;\n }\n\n //dragElm can't leave the screen on the bottom\n if (topElmPos + 10 > $params.document_height) {\n topElmPos = $params.document_height - 10;\n }\n\n //dragElm can't leave the screen on the right\n if (leftElmPos + 10 > $params.document_width) {\n leftElmPos = $params.document_width - 10;\n }\n\n $params.dragElm.css(\n {\n 'left': leftElmPos + _$scope.$callbacks.calsIndent(\n $params.offsetEdge + 1,\n true,\n true\n ) + 'px',\n 'top': topElmPos + 'px'\n }\n );\n\n if (_$scope.enabledStatus) {\n _$scope.setPositionStatus(e);\n }\n\n var top_scroll = window.pageYOffset || $params.$window.document.documentElement.scrollTop,\n bottom_scroll = top_scroll + (window.innerHeight || $params.$window.document.clientHeight || $params.$window.document.clientHeight);\n // to scroll down if cursor y-position is greater than the bottom position the vertical scroll\n if (bottom_scroll < eventObj.pageY && bottom_scroll <= $params.document_height) {\n window.scrollBy(0, 10);\n }\n // to scroll top if cursor y-position is less than the top position the vertical scroll\n if (top_scroll > eventObj.pageY) {\n window.scrollBy(0, -10);\n }\n\n $TreeDnDHelper.positionMoved(e, $params.pos, $params.firstMoving);\n\n if ($params.firstMoving) {\n $params.firstMoving = false;\n return;\n }\n // check if add it as a child node first\n\n var targetX = eventObj.pageX - $params.$window.document.body.scrollLeft,\n targetY = eventObj.pageY - (window.pageYOffset || $params.$window.document.documentElement.scrollTop),\n\n targetElm,\n targetScope,\n targetBefore,\n targetOffset,\n isChanged = true,\n isVeritcal = true,\n isEmpty,\n isSwapped,\n _scope,\n _target,\n _parent,\n _info = $params.dragInfo,\n _move = _info.move,\n _drag = _info.node,\n _drop = _info.drop,\n treeScope = _info.target,\n fnSwapTree,\n isHolder = _fnPlaceHolder(e, $params);\n\n if (!isHolder) {\n /* when using elementFromPoint() inside an iframe, you have to call\n elementFromPoint() twice to make sure IE8 returns the correct value\n $params.$window.document.elementFromPoint(targetX, targetY);*/\n\n targetElm = angular.element(\n $params.$window.document.elementFromPoint(\n targetX,\n targetY\n )\n );\n\n targetScope = targetElm.scope();\n if (!targetScope || !targetScope.$callbacks || !targetScope.$callbacks.droppable()) {\n // Not allowed Drop Item\n return;\n }\n\n fnSwapTree = function () {\n treeScope = targetScope.getScopeTree();\n _target = _info.target;\n\n if (_info.target !== treeScope) {\n // Replace by place-holder new\n _target.hidePlace();\n _target.targeting = false;\n treeScope.targeting = true;\n\n _info.target = treeScope;\n $params.placeElm = treeScope.initPlace(targetScope.$element, $params.dragElm);\n\n _target = null;\n isSwapped = true;\n }\n return true;\n };\n\n if (angular.isFunction(targetScope.getScopeNode)) {\n targetScope = targetScope.getScopeNode();\n if (!fnSwapTree()) {\n return;\n }\n } else {\n if (targetScope.$type === 'TreeDnDNodes' || targetScope.$type === 'TreeDnD') {\n if (targetScope.tree_nodes) {\n if (targetScope.tree_nodes.length === 0) {\n if (!fnSwapTree()) {\n return;\n }\n // Empty\n isEmpty = true;\n }\n } else {\n return;\n }\n } else {\n return;\n }\n }\n }\n\n if ($params.pos.dirAx && !isSwapped || isHolder) {\n isVeritcal = false;\n targetScope = _info.scope;\n }\n\n if (!targetScope.$element && !targetScope) {\n return;\n }\n\n if (isEmpty) {\n _move.parent = null;\n _move.pos = 0;\n\n _drop = null;\n } else {\n // move vertical\n if (isVeritcal) {\n targetElm = targetScope.$element; // Get the element of tree-dnd-node\n if (angular.isUndefinedOrNull(targetElm)) {\n return;\n }\n targetOffset = $TreeDnDHelper.offset(targetElm);\n\n if (targetScope.horizontal && !targetScope.isTable) {\n targetBefore = eventObj.pageX < targetOffset.left + $TreeDnDHelper.width(targetElm) / 2;\n } else {\n if (targetScope.isTable) {\n targetBefore = eventObj.pageY < targetOffset.top + $TreeDnDHelper.height(targetElm) / 2;\n } else {\n var _height = $TreeDnDHelper.height(targetElm);\n\n if (targetScope.getElementChilds()) {\n _height -= -$TreeDnDHelper.height(targetScope.getElementChilds());\n }\n\n if (eventObj.pageY > targetOffset.top + _height) {\n return;\n }\n\n targetBefore = eventObj.pageY < targetOffset.top + _height / 2;\n }\n }\n\n if (!angular.isFunction(targetScope.getData)) {\n return;\n }\n\n _target = targetScope.getData();\n _parent = targetScope.getNode(_target.__parent_real__);\n\n if (targetBefore) {\n var _prev = targetScope.getPrevSibling(_target);\n\n _move.parent = _parent;\n _move.pos = angular.isDefined(_prev) ? _prev.__index__ + 1 : 0;\n\n _drop = _prev;\n } else {\n if (_target.__expanded__ && !(_target.__children__.length === 1 && _target.__index_real__ === _drag.__parent_real__)) {\n _move.parent = _target;\n _move.pos = 0;\n\n _drop = null;\n } else {\n _move.parent = _parent;\n _move.pos = _target.__index__ + 1;\n\n _drop = _target;\n }\n }\n } else {\n // move horizontal\n if ($params.pos.dirAx && $params.pos.distAxX >= treeScope.dragBorder) {\n $params.pos.distAxX = 0;\n // increase horizontal level if previous sibling exists and is not collapsed\n if ($params.pos.distX > 0) {\n _parent = _drop;\n if (!_parent) {\n if (_move.pos - 1 >= 0) {\n _parent = _move.parent.__children__[_move.pos - 1];\n } else {\n return;\n }\n }\n\n if (_info.drag === _info.target && _parent === _drag && _$scope.enabledMove) {\n _parent = treeScope.getPrevSibling(_parent);\n }\n\n if (_parent && _parent.__visible__) {\n var _len = _parent.__children__.length;\n\n _move.parent = _parent;\n _move.pos = _len;\n\n if (_len > 0) {\n _drop = _parent.__children__[_len - 1];\n } else {\n _drop = null;\n }\n } else {\n // Not changed\n return;\n }\n } else if ($params.pos.distX < 0) {\n _target = _move.parent;\n if (_target &&\n (_target.__children__.length === 0 ||\n _target.__children__.length - 1 < _move.pos ||\n _info.drag === _info.target &&\n _target.__index_real__ === _drag.__parent_real__ &&\n _target.__children__.length - 1 === _drag.__index__ && _$scope.enabledMove)\n ) {\n _parent = treeScope.getNode(_target.__parent_real__);\n\n _move.parent = _parent;\n _move.pos = _target.__index__ + 1;\n\n _drop = _target;\n } else {\n // Not changed\n return;\n }\n } else {\n return;\n }\n } else {\n // limited\n return;\n }\n }\n }\n\n if (_info.drag === _info.target &&\n _move.parent &&\n _drag.__parent_real__ === _move.parent.__index_real__ &&\n _drag.__index__ === _move.pos\n ) {\n isChanged = false;\n }\n\n if (treeScope.$callbacks.accept(_info, _move, isChanged)) {\n _info.move = _move;\n _info.drop = _drop;\n _info.changed = isChanged;\n _info.scope = targetScope;\n\n if (targetScope.isTable) {\n $TreeDnDHelper.replaceIndent(\n treeScope,\n $params.placeElm,\n angular.isUndefinedOrNull(_move.parent) ? 1 : _move.parent.__level__ + 1\n );\n\n if (_drop) {\n _parent = (_move.parent ? _move.parent.__children__ : null ) || _info.target.treeData;\n\n if (_drop.__index__ < _parent.length - 1) {\n // Find fast\n _drop = _parent[_drop.__index__ + 1];\n _scope = _info.target.getScope(_drop);\n _scope.$element[0].parentNode.insertBefore(\n $params.placeElm[0],\n _scope.$element[0]\n );\n } else {\n _target = _info.target.getLastDescendant(_drop);\n _scope = _info.target.getScope(_target);\n _scope.$element.after($params.placeElm);\n }\n } else {\n _scope = _info.target.getScope(_move.parent);\n if (_scope) {\n if (_move.parent) {\n _scope.$element.after($params.placeElm);\n\n } else {\n _scope.getElementChilds().prepend($params.placeElm);\n }\n }\n }\n } else {\n _scope = _info.target.getScope(_drop || _move.parent);\n if (_drop) {\n _scope.$element.after($params.placeElm);\n } else {\n _scope.getElementChilds().prepend($params.placeElm);\n }\n }\n\n treeScope.showPlace();\n\n _$scope.$safeApply(\n function () {\n _$scope.$callbacks.dragMove(_info);\n }\n );\n }\n\n }\n }\n\n function _fnDragEnd(e, $params) {\n e.preventDefault();\n if ($params.dragElm) {\n var _passed = false,\n _$scope = $params.$scope,\n _scope = _$scope.getScope($params.dragInfo.node),\n _element = _scope.$element;\n\n _$scope.$safeApply(\n function () {\n _passed = _$scope.$callbacks.beforeDrop($params.dragInfo);\n }\n );\n\n // rollback all\n if (_scope.isTable) {\n _$scope.for_all_descendants(\n $params.dragInfo.node, function (_node, _parent) {\n _scope = _$scope.getScope(_node);\n _element = _scope && _scope.$element;\n if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) {\n if (_$scope.$class.hidden) {\n _element.removeClass(_$scope.$class.hidden);\n }\n }\n return _node.__visible__ === false || _node.__expanded__ === false\n }, null, true\n );\n } else {\n if (_$scope.$class.hidden) {\n _element.removeClass(_$scope.$class.hidden);\n }\n }\n\n $params.dragElm.remove();\n $params.dragElm = null;\n\n if (_$scope.enabledStatus) {\n _$scope.hideStatus();\n }\n\n if (_$scope.$$apply) {\n _$scope.$safeApply(\n function () {\n var _status = _$scope.$callbacks.dropped(\n $params.dragInfo,\n _passed\n );\n\n _$scope.$callbacks.dragStop($params.dragInfo, _status);\n clearData();\n }\n );\n } else {\n _fnBindDrag($params);\n _$scope.$safeApply(\n function () {\n _$scope.$callbacks.dragStop($params.dragInfo, false);\n clearData();\n }\n );\n }\n\n }\n\n function clearData() {\n $params.dragInfo.target.hidePlace();\n $params.dragInfo.target.targeting = false;\n\n $params.dragInfo = null;\n _$scope.$$apply = false;\n _$scope.setDragging(null);\n }\n\n angular.element($params.$document).unbind('touchend', $params.dragEndEvent); // Mobile\n angular.element($params.$document).unbind('touchcancel', $params.dragEndEvent); // Mobile\n angular.element($params.$document).unbind('touchmove', $params.dragMoveEvent); // Mobile\n angular.element($params.$document).unbind('mouseup', $params.dragEndEvent);\n angular.element($params.$document).unbind('mousemove', $params.dragMoveEvent);\n angular.element($params.$window.document.body).unbind('mouseleave', $params.dragCancelEvent);\n }\n\n function _fnDragStartEvent(e, $params) {\n if ($params.$scope.$callbacks.draggable()) {\n _fnDragStart(e, $params);\n }\n }\n\n function _fnBindDrag($params) {\n $params.element.bind(\n 'touchstart mousedown', function (e) {\n $params.dragDelaying = true;\n $params.dragStarted = false;\n _fnDragStartEvent(e, $params);\n $params.dragTimer = $timeout(\n function () {\n $params.dragDelaying = false;\n }, $params.$scope.dragDelay\n );\n }\n );\n\n $params.element.bind(\n 'touchend touchcancel mouseup', function () {\n $timeout.cancel($params.dragTimer);\n }\n );\n }\n\n function _fnKeydownHandler(e, $params) {\n var _$scope = $params.$scope;\n if (e.keyCode === 27) {\n if (_$scope.enabledStatus) {\n _$scope.hideStatus();\n }\n\n _$scope.$$apply = false;\n _fnDragEnd(e, $params);\n } else {\n if (_$scope.enabledHotkey && e.shiftKey) {\n _$scope.enableMove(true);\n if (_$scope.enabledStatus) {\n _$scope.refreshStatus();\n }\n\n if (!$params.dragInfo) {\n return;\n }\n\n var _scope = _$scope.getScope($params.dragInfo.node),\n _element = _scope.$element;\n\n if (_scope.isTable) {\n _$scope.for_all_descendants(\n $params.dragInfo.node, function (_node, _parent) {\n _scope = _$scope.getScope(_node);\n _element = _scope && _scope.$element;\n if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) {\n if (_$scope.$class.hidden) {\n _element.addClass(_$scope.$class.hidden);\n }\n }\n return _node.__visible__ === false || _node.__expanded__ === false\n\n }, null, true\n );\n } else {\n if (_$scope.$class.hidden) {\n _element.addClass(_$scope.$class.hidden);\n }\n }\n }\n }\n }\n\n function _fnKeyupHandler(e, $params) {\n var _$scope = $params.$scope;\n if (_$scope.enabledHotkey && !e.shiftKey) {\n _$scope.enableMove(false);\n\n if (_$scope.enabledStatus) {\n _$scope.refreshStatus();\n }\n\n if (!$params.dragInfo) {\n return;\n }\n\n var _scope = _$scope.getScope($params.dragInfo.node),\n _element = _scope.$element;\n\n if (_scope.isTable) {\n _$scope.for_all_descendants(\n $params.dragInfo.node, function (_node, _parent) {\n _scope = _$scope.getScope(_node);\n _element = _scope && _scope.$element;\n if (_scope && _element && (!_parent && _node.__visible__ || _parent.__expanded__)) {\n if (_$scope.$class.hidden) {\n _element.removeClass(_$scope.$class.hidden);\n }\n }\n return _node.__visible__ === false || _node.__expanded__ === false\n }, null, true\n );\n } else {\n if (_$scope.$class.hidden) {\n _element.removeClass(_$scope.$class.hidden);\n }\n }\n }\n }\n\n function _$init(scope, element, $window, $document) {\n var $params = {\n hasTouch: 'ontouchstart' in window,\n firstMoving: null,\n dragInfo: null,\n pos: null,\n placeElm: null,\n dragElm: null,\n dragDelaying: true,\n dragStarted: false,\n dragTimer: null,\n body: document.body,\n html: document.documentElement,\n document_height: null,\n document_width: null,\n offsetEdge: null,\n $scope: scope,\n $window: $window,\n $document: $document,\n element: element,\n bindDrag: function () {\n _fnBindDrag($params);\n },\n dragEnd: function (e) {\n _fnDragEnd(e, $params);\n },\n dragMoveEvent: function (e) {\n _fnDragMove(e, $params);\n },\n dragEndEvent: function (e) {\n scope.$$apply = true;\n _fnDragEnd(e, $params);\n },\n dragCancelEvent: function (e) {\n _fnDragEnd(e, $params);\n }\n },\n keydownHandler = function (e) {\n return _fnKeydownHandler(e, $params);\n },\n keyupHandler = function (e) {\n return _fnKeyupHandler(e, $params);\n };\n\n scope.dragEnd = function (e) {\n $params.dragEnd(e);\n };\n\n $params.bindDrag();\n\n angular.element($window.document.body).bind('keydown', keydownHandler);\n angular.element($window.document.body).bind('keyup', keyupHandler);\n //unbind handler that retains scope\n scope.$on(\n '$destroy', function () {\n angular.element($window.document.body).unbind('keydown', keydownHandler);\n angular.element($window.document.body).unbind('keyup', keyupHandler);\n if (scope.statusElm) {\n scope.statusElm.remove();\n }\n\n if (scope.placeElm) {\n scope.placeElm.remove();\n }\n }\n );\n }\n\n return _$init;\n }\n ]\n);\n\nangular.module('ntt.TreeDnD')\n .factory(\n '$TreeDnDControl', function () {\n var _target, _parent,\n i, len;\n\n function fnSetCollapse(node) {\n node.__expanded__ = false;\n }\n\n function fnSetExpand(node) {\n node.__expanded__ = true;\n }\n\n function _$init(scope) {\n var n, tree = {\n selected_node: null,\n for_all_descendants: scope.for_all_descendants,\n select_node: function (node) {\n if (!node) {\n if (tree.selected_node) {\n delete tree.selected_node.__selected__;\n }\n tree.selected_node = null;\n return null;\n }\n\n if (node !== tree.selected_node) {\n if (tree.selected_node) {\n delete tree.selected_node.__selected__;\n }\n node.__selected__ = true;\n tree.selected_node = node;\n tree.expand_all_parents(node);\n if (angular.isFunction(tree.on_select)) {\n tree.on_select(node);\n }\n }\n return node;\n },\n deselect_node: function () {\n _target = null;\n if (tree.selected_node) {\n delete tree.selected_node.__selected__;\n _target = tree.selected_node;\n tree.selected_node = null;\n }\n return _target;\n },\n get_parent: function (node) {\n if (node && node.__parent_real__ !== null) {\n return scope.tree_nodes[node.__parent_real__];\n }\n return null;\n },\n for_all_ancestors: function (child, fn) {\n _parent = tree.get_parent(child);\n if (_parent) {\n if (fn(_parent)) {\n return false;\n }\n\n return tree.for_all_ancestors(_parent, fn);\n }\n return true;\n },\n expand_all_parents: function (child) {\n child = child || tree.selected_node;\n if (typeof child === 'object') {\n tree.for_all_ancestors(\n child, fnSetExpand\n )\n }\n },\n collapse_all_parents: function (child) {\n child = child || tree.selected_node;\n if (typeof child === 'object') {\n tree.for_all_ancestors(\n child, fnSetCollapse\n )\n }\n },\n\n reload_data: function () {\n return scope.reload_data();\n },\n add_node: function (parent, new_node, index) {\n if (typeof index !== 'number') {\n if (parent) {\n parent.__children__.push(new_node);\n parent.__expanded__ = true;\n } else {\n scope.treeData.push(new_node);\n }\n } else {\n if (parent) {\n parent.__children__.splice(index, 0, new_node);\n parent.__expanded__ = true;\n } else {\n scope.treeData.splice(index, 0, new_node);\n }\n }\n return new_node;\n },\n add_node_root: function (new_node) {\n tree.add_node(null, new_node);\n return new_node;\n },\n expand_all: function () {\n len = scope.treeData.length;\n for (i = 0; i < len; i++) {\n tree.for_all_descendants(\n scope.treeData[i], fnSetExpand\n );\n }\n },\n collapse_all: function () {\n len = scope.treeData.length;\n for (i = 0; i < len; i++) {\n tree.for_all_descendants(\n scope.treeData[i], fnSetCollapse\n );\n }\n },\n remove_node: function (node) {\n node = node || tree.selected_node;\n if (typeof node === 'object') {\n if (node.__parent_real__ !== null) {\n _parent = tree.get_parent(node).__children__;\n } else {\n _parent = scope.treeData;\n }\n\n _parent.splice(node.__index__, 1);\n\n tree.reload_data();\n\n if (tree.selected_node === node) {\n tree.selected_node = null;\n }\n }\n },\n expand_node: function (node) {\n node = node || tree.selected_node;\n if (typeof node === 'object' && node.__expanded__) {\n node.__expanded__ = true;\n return node;\n }\n },\n collapse_node: function (node) {\n node = node || tree.selected_node;\n if (typeof node === 'object') {\n node.__expanded__ = false;\n return node;\n }\n },\n get_selected_node: function () {\n return tree.selected_node;\n },\n get_first_node: function () {\n len = scope.treeData.length;\n if (len > 0) {\n return scope.treeData[0];\n }\n return null;\n },\n get_children: function (node) {\n return node.__children__;\n },\n get_siblings: function (node) {\n node = node || tree.selected_node;\n if (typeof node === 'object') {\n _parent = tree.get_parent(node);\n if (_parent) {\n _target = _parent.__children__;\n } else {\n _target = scope.treeData;\n }\n return _target;\n }\n },\n get_next_sibling: function (node) {\n node = node || tree.selected_node;\n if (typeof node === 'object') {\n _target = tree.get_siblings(node);\n n = _target.length;\n if (node.__index__ < n) {\n return _target[node.__index__ + 1];\n }\n }\n },\n get_prev_sibling: function (node) {\n node = node || tree.selected_node;\n _target = tree.get_siblings(node);\n if (node.__index__ > 0) {\n return _target[node.__index__ - 1];\n }\n },\n get_first_child: function (node) {\n node = node || tree.selected_node;\n if (typeof node === 'object') {\n _target = node.__children__;\n if (_target && _target.length > 0) {\n return node.__children__[0];\n }\n }\n return null;\n },\n get_closest_ancestor_next_sibling: function (node) {\n node = node || tree.selected_node;\n _target = tree.get_next_sibling(node);\n if (_target) {\n return _target;\n }\n\n _parent = tree.get_parent(node);\n return tree.get_closest_ancestor_next_sibling(_parent);\n },\n get_next_node: function (node) {\n node = node || tree.selected_node;\n\n if (typeof node === 'object') {\n _target = tree.get_first_child(node);\n if (_target) {\n return _target;\n } else {\n return tree.get_closest_ancestor_next_sibling(node);\n }\n }\n },\n get_prev_node: function (node) {\n node = node || tree.selected_node;\n\n if (typeof node === 'object') {\n _target = tree.get_prev_sibling(node);\n if (_target) {\n return tree.get_last_descendant(_target);\n }\n\n _parent = tree.get_parent(node);\n return _parent;\n }\n },\n get_last_descendant: scope.getLastDescendant,\n select_parent_node: function (node) {\n node = node || tree.selected_node;\n\n if (typeof node === 'object') {\n _parent = tree.get_parent(node);\n if (_parent) {\n return tree.select_node(_parent);\n }\n }\n },\n select_first_node: function () {\n var firstNode = tree.get_first_node();\n return tree.select_node(firstNode);\n },\n select_next_sibling: function (node) {\n node = node || tree.selected_node;\n\n if (typeof node === 'object') {\n _target = tree.get_next_sibling(node);\n if (_target) {\n return tree.select_node(_target);\n }\n }\n },\n select_prev_sibling: function (node) {\n node = node || tree.selected_node;\n\n if (typeof node === 'object') {\n _target = tree.get_prev_sibling(node);\n if (_target) {\n return tree.select_node(_target);\n }\n }\n },\n select_next_node: function (node) {\n node = node || tree.selected_node;\n\n if (typeof node === 'object') {\n _target = tree.get_next_node(node);\n if (_target) {\n return tree.select_node(_target);\n }\n }\n },\n select_prev_node: function (node) {\n node = node || tree.selected_node;\n\n if (typeof node === 'object') {\n _target = tree.get_prev_node(node);\n if (_target) {\n return tree.select_node(_target);\n }\n }\n }\n };\n angular.extend(scope.tree, tree);\n return scope.tree;\n }\n\n return _$init;\n }\n);\n\nangular.module('template/TreeDnD/TreeDnD.html', []).run(\n [\n '$templateCache', function ($templateCache) {\n $templateCache.put(\n 'template/TreeDnD/TreeDnD.html',\n ['',\n ' ',\n ' ',\n ' ',\n ' ',\n ' ',\n ' ',\n ' ',\n ' ',\n ' ',\n ' ',\n ' ',\n '
',\n ' {{expandingProperty.displayName || expandingProperty.field || expandingProperty}}',\n ' <\\/th>',\n ' ',\n ' {{col.displayName || col.field}}',\n '
',\n ' ',\n ' ',\n ' ',\n ' {{node[expandingProperty.field] || node[expandingProperty]}}',\n ' ',\n ' {{node[col.field]}}',\n '
'].join('\\n')\n );\n\n $templateCache.put(\n 'template/TreeDnD/TreeDnDStatusCopy.html',\n ''\n );\n\n $templateCache.put(\n 'template/TreeDnD/TreeDnDStatusMove.html',\n ''\n );\n }]\n);\n\n function isUndefinedOrNull(val) {\n return angular.isUndefined(val) || val === null;\n }\n\n function isDefined(val) {\n return !(angular.isUndefined(val) || val === null);\n }\n})();"],"sourceRoot":"/source/"} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-ui-bootstrap/ui-bootstrap-tpls-2.5.0.min.js b/src/main/resources/static/module/angular-ui-bootstrap/ui-bootstrap-tpls-2.5.0.min.js new file mode 100644 index 0000000..0b1fc7f --- /dev/null +++ b/src/main/resources/static/module/angular-ui-bootstrap/ui-bootstrap-tpls-2.5.0.min.js @@ -0,0 +1,10 @@ +/* + * angular-ui-bootstrap + * http://angular-ui.github.io/bootstrap/ + + * Version: 2.5.0 - 2017-01-28 + * License: MIT + */angular.module("ui.bootstrap",["ui.bootstrap.tpls","ui.bootstrap.collapse","ui.bootstrap.tabindex","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.isClass","ui.bootstrap.datepicker","ui.bootstrap.position","ui.bootstrap.datepickerPopup","ui.bootstrap.debounce","ui.bootstrap.multiMap","ui.bootstrap.dropdown","ui.bootstrap.stackedMap","ui.bootstrap.modal","ui.bootstrap.paging","ui.bootstrap.pager","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]),angular.module("ui.bootstrap.tpls",["uib/template/accordion/accordion-group.html","uib/template/accordion/accordion.html","uib/template/alert/alert.html","uib/template/carousel/carousel.html","uib/template/carousel/slide.html","uib/template/datepicker/datepicker.html","uib/template/datepicker/day.html","uib/template/datepicker/month.html","uib/template/datepicker/year.html","uib/template/datepickerPopup/popup.html","uib/template/modal/window.html","uib/template/pager/pager.html","uib/template/pagination/pagination.html","uib/template/tooltip/tooltip-html-popup.html","uib/template/tooltip/tooltip-popup.html","uib/template/tooltip/tooltip-template-popup.html","uib/template/popover/popover-html.html","uib/template/popover/popover-template.html","uib/template/popover/popover.html","uib/template/progressbar/bar.html","uib/template/progressbar/progress.html","uib/template/progressbar/progressbar.html","uib/template/rating/rating.html","uib/template/tabs/tab.html","uib/template/tabs/tabset.html","uib/template/timepicker/timepicker.html","uib/template/typeahead/typeahead-match.html","uib/template/typeahead/typeahead-popup.html"]),angular.module("ui.bootstrap.collapse",[]).directive("uibCollapse",["$animate","$q","$parse","$injector",function(a,b,c,d){var e=d.has("$animateCss")?d.get("$animateCss"):null;return{link:function(d,f,g){function h(){r=!!("horizontal"in g),r?(s={width:""},t={width:"0"}):(s={height:""},t={height:"0"}),d.$eval(g.uibCollapse)||f.addClass("in").addClass("collapse").attr("aria-expanded",!0).attr("aria-hidden",!1).css(s)}function i(a){return r?{width:a.scrollWidth+"px"}:{height:a.scrollHeight+"px"}}function j(){f.hasClass("collapse")&&f.hasClass("in")||b.resolve(n(d)).then(function(){f.removeClass("collapse").addClass("collapsing").attr("aria-expanded",!0).attr("aria-hidden",!1),e?e(f,{addClass:"in",easing:"ease",css:{overflow:"hidden"},to:i(f[0])}).start()["finally"](k):a.addClass(f,"in",{css:{overflow:"hidden"},to:i(f[0])}).then(k)},angular.noop)}function k(){f.removeClass("collapsing").addClass("collapse").css(s),o(d)}function l(){return f.hasClass("collapse")||f.hasClass("in")?void b.resolve(p(d)).then(function(){f.css(i(f[0])).removeClass("collapse").addClass("collapsing").attr("aria-expanded",!1).attr("aria-hidden",!0),e?e(f,{removeClass:"in",to:t}).start()["finally"](m):a.removeClass(f,"in",{to:t}).then(m)},angular.noop):m()}function m(){f.css(t),f.removeClass("collapsing").addClass("collapse"),q(d)}var n=c(g.expanding),o=c(g.expanded),p=c(g.collapsing),q=c(g.collapsed),r=!1,s={},t={};h(),d.$watch(g.uibCollapse,function(a){a?l():j()})}}}]),angular.module("ui.bootstrap.tabindex",[]).directive("uibTabindexToggle",function(){return{restrict:"A",link:function(a,b,c){c.$observe("disabled",function(a){c.$set("tabindex",a?-1:null)})}}}),angular.module("ui.bootstrap.accordion",["ui.bootstrap.collapse","ui.bootstrap.tabindex"]).constant("uibAccordionConfig",{closeOthers:!0}).controller("UibAccordionController",["$scope","$attrs","uibAccordionConfig",function(a,b,c){this.groups=[],this.closeOthers=function(d){var e=angular.isDefined(b.closeOthers)?a.$eval(b.closeOthers):c.closeOthers;e&&angular.forEach(this.groups,function(a){a!==d&&(a.isOpen=!1)})},this.addGroup=function(a){var b=this;this.groups.push(a),a.$on("$destroy",function(c){b.removeGroup(a)})},this.removeGroup=function(a){var b=this.groups.indexOf(a);-1!==b&&this.groups.splice(b,1)}}]).directive("uibAccordion",function(){return{controller:"UibAccordionController",controllerAs:"accordion",transclude:!0,templateUrl:function(a,b){return b.templateUrl||"uib/template/accordion/accordion.html"}}}).directive("uibAccordionGroup",function(){return{require:"^uibAccordion",transclude:!0,restrict:"A",templateUrl:function(a,b){return b.templateUrl||"uib/template/accordion/accordion-group.html"},scope:{heading:"@",panelClass:"@?",isOpen:"=?",isDisabled:"=?"},controller:function(){this.setHeading=function(a){this.heading=a}},link:function(a,b,c,d){b.addClass("panel"),d.addGroup(a),a.openClass=c.openClass||"panel-open",a.panelClass=c.panelClass||"panel-default",a.$watch("isOpen",function(c){b.toggleClass(a.openClass,!!c),c&&d.closeOthers(a)}),a.toggleOpen=function(b){a.isDisabled||b&&32!==b.which||(a.isOpen=!a.isOpen)};var e="accordiongroup-"+a.$id+"-"+Math.floor(1e4*Math.random());a.headingId=e+"-tab",a.panelId=e+"-panel"}}}).directive("uibAccordionHeading",function(){return{transclude:!0,template:"",replace:!0,require:"^uibAccordionGroup",link:function(a,b,c,d,e){d.setHeading(e(a,angular.noop))}}}).directive("uibAccordionTransclude",function(){function a(){return"uib-accordion-header,data-uib-accordion-header,x-uib-accordion-header,uib\\:accordion-header,[uib-accordion-header],[data-uib-accordion-header],[x-uib-accordion-header]"}return{require:"^uibAccordionGroup",link:function(b,c,d,e){b.$watch(function(){return e[d.uibAccordionTransclude]},function(b){if(b){var d=angular.element(c[0].querySelector(a()));d.html(""),d.append(b)}})}}}),angular.module("ui.bootstrap.alert",[]).controller("UibAlertController",["$scope","$element","$attrs","$interpolate","$timeout",function(a,b,c,d,e){a.closeable=!!c.close,b.addClass("alert"),c.$set("role","alert"),a.closeable&&b.addClass("alert-dismissible");var f=angular.isDefined(c.dismissOnTimeout)?d(c.dismissOnTimeout)(a.$parent):null;f&&e(function(){a.close()},parseInt(f,10))}]).directive("uibAlert",function(){return{controller:"UibAlertController",controllerAs:"alert",restrict:"A",templateUrl:function(a,b){return b.templateUrl||"uib/template/alert/alert.html"},transclude:!0,scope:{close:"&"}}}),angular.module("ui.bootstrap.buttons",[]).constant("uibButtonConfig",{activeClass:"active",toggleEvent:"click"}).controller("UibButtonsController",["uibButtonConfig",function(a){this.activeClass=a.activeClass||"active",this.toggleEvent=a.toggleEvent||"click"}]).directive("uibBtnRadio",["$parse",function(a){return{require:["uibBtnRadio","ngModel"],controller:"UibButtonsController",controllerAs:"buttons",link:function(b,c,d,e){var f=e[0],g=e[1],h=a(d.uibUncheckable);c.find("input").css({display:"none"}),g.$render=function(){c.toggleClass(f.activeClass,angular.equals(g.$modelValue,b.$eval(d.uibBtnRadio)))},c.on(f.toggleEvent,function(){if(!d.disabled){var a=c.hasClass(f.activeClass);a&&!angular.isDefined(d.uncheckable)||b.$apply(function(){g.$setViewValue(a?null:b.$eval(d.uibBtnRadio)),g.$render()})}}),d.uibUncheckable&&b.$watch(h,function(a){d.$set("uncheckable",a?"":void 0)})}}}]).directive("uibBtnCheckbox",function(){return{require:["uibBtnCheckbox","ngModel"],controller:"UibButtonsController",controllerAs:"button",link:function(a,b,c,d){function e(){return g(c.btnCheckboxTrue,!0)}function f(){return g(c.btnCheckboxFalse,!1)}function g(b,c){return angular.isDefined(b)?a.$eval(b):c}var h=d[0],i=d[1];b.find("input").css({display:"none"}),i.$render=function(){b.toggleClass(h.activeClass,angular.equals(i.$modelValue,e()))},b.on(h.toggleEvent,function(){c.disabled||a.$apply(function(){i.$setViewValue(b.hasClass(h.activeClass)?f():e()),i.$render()})})}}}),angular.module("ui.bootstrap.carousel",[]).controller("UibCarouselController",["$scope","$element","$interval","$timeout","$animate",function(a,b,c,d,e){function f(a){for(var b=0;b1){p[d].element.data(q,c.direction);var h=o.getCurrentIndex();angular.isNumber(h)&&p[h].element&&p[h].element.data(q,c.direction),a.$currentTransition=!0,e.on("addClass",p[d].element,function(b,c){"close"===c&&(a.$currentTransition=null,e.off("addClass",b))})}a.active=c.index,r=c.index,f(d),k()}}function h(a){for(var b=0;b0&&(m=c(l,b))}function l(){var b=+a.interval;n&&!isNaN(b)&&b>0&&p.length?a.next():a.pause()}var m,n,o=this,p=o.slides=a.slides=[],q="uib-slideDirection",r=a.active,s=!1;b.addClass("carousel"),o.addSlide=function(b,c){p.push({slide:b,element:c}),p.sort(function(a,b){return+a.slide.index-+b.slide.index}),(b.index===a.active||1===p.length&&!angular.isNumber(a.active))&&(a.$currentTransition&&(a.$currentTransition=null),r=b.index,a.active=b.index,f(r),o.select(p[h(b)]),1===p.length&&a.play())},o.getCurrentIndex=function(){for(var a=0;a0&&r===c?c>=p.length?(r=p.length-1,a.active=r,f(r),o.select(p[p.length-1])):(r=c,a.active=r,f(r),o.select(p[c])):r>c&&(r--,a.active=r),0===p.length&&(r=null,a.active=null)},o.select=a.select=function(b,c){var d=h(b.slide);void 0===c&&(c=d>o.getCurrentIndex()?"next":"prev"),b.slide.index===r||a.$currentTransition||g(b.slide,d,c)},a.indexOfSlide=function(a){return+a.slide.index},a.isActive=function(b){return a.active===b.slide.index},a.isPrevDisabled=function(){return 0===a.active&&a.noWrap()},a.isNextDisabled=function(){return a.active===p.length-1&&a.noWrap()},a.pause=function(){a.noPause||(n=!1,i())},a.play=function(){n||(n=!0,k())},b.on("mouseenter",a.pause),b.on("mouseleave",a.play),a.$on("$destroy",function(){s=!0,i()}),a.$watch("noTransition",function(a){e.enabled(b,!a)}),a.$watch("interval",k),a.$watchCollection("slides",j),a.$watch("active",function(a){if(angular.isNumber(a)&&r!==a){for(var b=0;b-1){var f=!1;a=a.split("");for(var g=e;g-1){a=a.split(""),c[e]="("+d.regex+")",a[e]="$";for(var f=e+1,g=e+d.key.length;g>f;f++)c[f]="",a[f]="$";a=a.join(""),b.push({index:e,key:d.key,apply:d.apply,matcher:d.regex})}}),{regex:new RegExp("^"+c.join("")+"$"),map:d(b,"index")}}function h(a){for(var b,c,d=[],e=0;e=a.length||"'"!==a.charAt(e+1))&&(d.push(i(a,c,e)),c=null);else if(e===a.length)for(;cc?!1:1===b&&c>28?29===c&&(a%4===0&&a%100!==0||a%400===0):3===b||5===b||8===b||10===b?31>c:!0}function l(a){return parseInt(a,10)}function m(a,b){return a&&b?q(a,b):a}function n(a,b){return a&&b?q(a,b,!0):a}function o(a,b){a=a.replace(/:/g,"");var c=Date.parse("Jan 01, 1970 00:00:00 "+a)/6e4;return isNaN(c)?b:c}function p(a,b){return a=new Date(a.getTime()),a.setMinutes(a.getMinutes()+b),a}function q(a,b,c){c=c?-1:1;var d=a.getTimezoneOffset(),e=o(b,d);return p(a,c*(e-d))}var r,s,t=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;this.init=function(){r=b.id,this.parsers={},this.formatters={},s=[{key:"yyyy",regex:"\\d{4}",apply:function(a){this.year=+a},formatter:function(a){var b=new Date;return b.setFullYear(Math.abs(a.getFullYear())),c(b,"yyyy")}},{key:"yy",regex:"\\d{2}",apply:function(a){a=+a,this.year=69>a?a+2e3:a+1900},formatter:function(a){var b=new Date;return b.setFullYear(Math.abs(a.getFullYear())),c(b,"yy")}},{key:"y",regex:"\\d{1,4}",apply:function(a){this.year=+a},formatter:function(a){var b=new Date;return b.setFullYear(Math.abs(a.getFullYear())),c(b,"y")}},{key:"M!",regex:"0?[1-9]|1[0-2]",apply:function(a){this.month=a-1},formatter:function(a){var b=a.getMonth();return/^[0-9]$/.test(b)?c(a,"MM"):c(a,"M")}},{key:"MMMM",regex:b.DATETIME_FORMATS.MONTH.join("|"),apply:function(a){this.month=b.DATETIME_FORMATS.MONTH.indexOf(a)},formatter:function(a){return c(a,"MMMM")}},{key:"MMM",regex:b.DATETIME_FORMATS.SHORTMONTH.join("|"),apply:function(a){this.month=b.DATETIME_FORMATS.SHORTMONTH.indexOf(a)},formatter:function(a){return c(a,"MMM")}},{key:"MM",regex:"0[1-9]|1[0-2]",apply:function(a){this.month=a-1},formatter:function(a){return c(a,"MM")}},{key:"M",regex:"[1-9]|1[0-2]",apply:function(a){this.month=a-1},formatter:function(a){return c(a,"M")}},{key:"d!",regex:"[0-2]?[0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a},formatter:function(a){var b=a.getDate();return/^[1-9]$/.test(b)?c(a,"dd"):c(a,"d")}},{key:"dd",regex:"[0-2][0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a},formatter:function(a){return c(a,"dd")}},{key:"d",regex:"[1-2]?[0-9]{1}|3[0-1]{1}",apply:function(a){this.date=+a},formatter:function(a){return c(a,"d")}},{key:"EEEE",regex:b.DATETIME_FORMATS.DAY.join("|"),formatter:function(a){return c(a,"EEEE")}},{key:"EEE",regex:b.DATETIME_FORMATS.SHORTDAY.join("|"),formatter:function(a){return c(a,"EEE")}},{key:"HH",regex:"(?:0|1)[0-9]|2[0-3]",apply:function(a){this.hours=+a},formatter:function(a){return c(a,"HH")}},{key:"hh",regex:"0[0-9]|1[0-2]",apply:function(a){this.hours=+a},formatter:function(a){return c(a,"hh")}},{key:"H",regex:"1?[0-9]|2[0-3]",apply:function(a){this.hours=+a},formatter:function(a){return c(a,"H")}},{key:"h",regex:"[0-9]|1[0-2]",apply:function(a){this.hours=+a},formatter:function(a){return c(a,"h")}},{key:"mm",regex:"[0-5][0-9]",apply:function(a){this.minutes=+a},formatter:function(a){return c(a,"mm")}},{key:"m",regex:"[0-9]|[1-5][0-9]",apply:function(a){this.minutes=+a},formatter:function(a){return c(a,"m")}},{key:"sss",regex:"[0-9][0-9][0-9]",apply:function(a){this.milliseconds=+a},formatter:function(a){return c(a,"sss")}},{key:"ss",regex:"[0-5][0-9]",apply:function(a){this.seconds=+a},formatter:function(a){return c(a,"ss")}},{key:"s",regex:"[0-9]|[1-5][0-9]",apply:function(a){this.seconds=+a},formatter:function(a){return c(a,"s")}},{key:"a",regex:b.DATETIME_FORMATS.AMPMS.join("|"),apply:function(a){12===this.hours&&(this.hours=0),"PM"===a&&(this.hours+=12)},formatter:function(a){return c(a,"a")}},{key:"Z",regex:"[+-]\\d{4}",apply:function(a){var b=a.match(/([+-])(\d{2})(\d{2})/),c=b[1],d=b[2],e=b[3];this.hours+=l(c+d),this.minutes+=l(c+e)},formatter:function(a){return c(a,"Z")}},{key:"ww",regex:"[0-4][0-9]|5[0-3]",formatter:function(a){return c(a,"ww")}},{key:"w",regex:"[0-9]|[1-4][0-9]|5[0-3]",formatter:function(a){return c(a,"w")}},{key:"GGGG",regex:b.DATETIME_FORMATS.ERANAMES.join("|").replace(/\s/g,"\\s"),formatter:function(a){return c(a,"GGGG")}},{key:"GGG",regex:b.DATETIME_FORMATS.ERAS.join("|"),formatter:function(a){return c(a,"GGG")}},{key:"GG",regex:b.DATETIME_FORMATS.ERAS.join("|"),formatter:function(a){return c(a,"GG")}},{key:"G",regex:b.DATETIME_FORMATS.ERAS.join("|"),formatter:function(a){return c(a,"G")}}],angular.version.major>=1&&angular.version.minor>4&&s.push({key:"LLLL",regex:b.DATETIME_FORMATS.STANDALONEMONTH.join("|"),apply:function(a){this.month=b.DATETIME_FORMATS.STANDALONEMONTH.indexOf(a)},formatter:function(a){return c(a,"LLLL")}})},this.init(),this.getParser=function(a){var b=f(a);return b&&b.apply||null},this.overrideParser=function(a,b){var c=f(a);c&&angular.isFunction(b)&&(this.parsers={},c.apply=b)}.bind(this),this.filter=function(a,c){if(!angular.isDate(a)||isNaN(a)||!c)return"";c=b.DATETIME_FORMATS[c]||c,b.id!==r&&this.init(),this.formatters[c]||(this.formatters[c]=h(c));var d=this.formatters[c];return d.reduce(function(b,c){return b+c(a)},"")},this.parse=function(c,d,e){if(!angular.isString(c)||!d)return c;d=b.DATETIME_FORMATS[d]||d,d=d.replace(t,"\\$&"),b.id!==r&&this.init(),this.parsers[d]||(this.parsers[d]=g(d,"apply"));var f=this.parsers[d],h=f.regex,i=f.map,j=c.match(h),l=!1;if(j&&j.length){var m,n;angular.isDate(e)&&!isNaN(e.getTime())?m={year:e.getFullYear(),month:e.getMonth(),date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes(),seconds:e.getSeconds(),milliseconds:e.getMilliseconds()}:(e&&a.warn("dateparser:","baseDate is not a valid date"),m={year:1900,month:0,date:1,hours:0,minutes:0,seconds:0,milliseconds:0});for(var o=1,p=j.length;p>o;o++){var q=i[o-1];"Z"===q.matcher&&(l=!0),q.apply&&q.apply.call(m,j[o])}var s=l?Date.prototype.setUTCFullYear:Date.prototype.setFullYear,u=l?Date.prototype.setUTCHours:Date.prototype.setHours;return k(m.year,m.month,m.date)&&(!angular.isDate(e)||isNaN(e.getTime())||l?(n=new Date(0),s.call(n,m.year,m.month,m.date),u.call(n,m.hours||0,m.minutes||0,m.seconds||0,m.milliseconds||0)):(n=new Date(e),s.call(n,m.year,m.month,m.date),u.call(n,m.hours,m.minutes,m.seconds,m.milliseconds))),n}},this.toTimezone=m,this.fromTimezone=n,this.timezoneToOffset=o,this.addDateMinutes=p,this.convertTimezoneToLocal=q}]),angular.module("ui.bootstrap.isClass",[]).directive("uibIsClass",["$animate",function(a){var b=/^\s*([\s\S]+?)\s+on\s+([\s\S]+?)\s*$/,c=/^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/;return{restrict:"A",compile:function(d,e){function f(a,b,c){i.push(a),j.push({scope:a,element:b}),o.forEach(function(b,c){g(b,a)}),a.$on("$destroy",h)}function g(b,d){var e=b.match(c),f=d.$eval(e[1]),g=e[2],h=k[b];if(!h){var i=function(b){var c=null;j.some(function(a){var d=a.scope.$eval(m);return d===b?(c=a,!0):void 0}),h.lastActivated!==c&&(h.lastActivated&&a.removeClass(h.lastActivated.element,f),c&&a.addClass(c.element,f),h.lastActivated=c)};k[b]=h={lastActivated:null,scope:d,watchFn:i,compareWithExp:g,watcher:d.$watch(g,i)}}h.watchFn(d.$eval(g))}function h(a){var b=a.targetScope,c=i.indexOf(b);if(i.splice(c,1),j.splice(c,1),i.length){var d=i[0];angular.forEach(k,function(a){a.scope===b&&(a.watcher=d.$watch(a.compareWithExp,a.watchFn),a.scope=d)})}else k={}}var i=[],j=[],k={},l=e.uibIsClass.match(b),m=l[2],n=l[1],o=n.split(",");return f}}}]),angular.module("ui.bootstrap.datepicker",["ui.bootstrap.dateparser","ui.bootstrap.isClass"]).value("$datepickerSuppressError",!1).value("$datepickerLiteralWarning",!0).constant("uibDatepickerConfig",{datepickerMode:"day",formatDay:"dd",formatMonth:"MMMM",formatYear:"yyyy",formatDayHeader:"EEE",formatDayTitle:"MMMM yyyy",formatMonthTitle:"yyyy",maxDate:null,maxMode:"year",minDate:null,minMode:"day",monthColumns:3,ngModelOptions:{},shortcutPropagation:!1,showWeeks:!0,yearColumns:5,yearRows:4}).controller("UibDatepickerController",["$scope","$element","$attrs","$parse","$interpolate","$locale","$log","dateFilter","uibDatepickerConfig","$datepickerLiteralWarning","$datepickerSuppressError","uibDateParser",function(a,b,c,d,e,f,g,h,i,j,k,l){function m(b){a.datepickerMode=b,a.datepickerOptions.datepickerMode=b}function n(b){var c;if(angular.version.minor<6)c=b.$options||a.datepickerOptions.ngModelOptions||i.ngModelOptions||{},c.getOption=function(a){return c[a]};else{var d=b.$options.getOption("timezone")||(a.datepickerOptions.ngModelOptions?a.datepickerOptions.ngModelOptions.timezone:null)||(i.ngModelOptions?i.ngModelOptions.timezone:null);c=b.$options.createChild(i.ngModelOptions).createChild(a.datepickerOptions.ngModelOptions).createChild(b.$options).createChild({timezone:d})}return c}var o=this,p={$setViewValue:angular.noop},q={},r=[];b.addClass("uib-datepicker"),c.$set("role","application"),a.datepickerOptions||(a.datepickerOptions={}),this.modes=["day","month","year"],["customClass","dateDisabled","datepickerMode","formatDay","formatDayHeader","formatDayTitle","formatMonth","formatMonthTitle","formatYear","maxDate","maxMode","minDate","minMode","monthColumns","showWeeks","shortcutPropagation","startingDay","yearColumns","yearRows"].forEach(function(b){switch(b){case"customClass":case"dateDisabled":a[b]=a.datepickerOptions[b]||angular.noop;break;case"datepickerMode":a.datepickerMode=angular.isDefined(a.datepickerOptions.datepickerMode)?a.datepickerOptions.datepickerMode:i.datepickerMode;break;case"formatDay":case"formatDayHeader":case"formatDayTitle":case"formatMonth":case"formatMonthTitle":case"formatYear":o[b]=angular.isDefined(a.datepickerOptions[b])?e(a.datepickerOptions[b])(a.$parent):i[b];break;case"monthColumns":case"showWeeks":case"shortcutPropagation":case"yearColumns":case"yearRows":o[b]=angular.isDefined(a.datepickerOptions[b])?a.datepickerOptions[b]:i[b];break;case"startingDay":angular.isDefined(a.datepickerOptions.startingDay)?o.startingDay=a.datepickerOptions.startingDay:angular.isNumber(i.startingDay)?o.startingDay=i.startingDay:o.startingDay=(f.DATETIME_FORMATS.FIRSTDAYOFWEEK+8)%7;break;case"maxDate":case"minDate":a.$watch("datepickerOptions."+b,function(a){a?angular.isDate(a)?o[b]=l.fromTimezone(new Date(a),q.getOption("timezone")):(j&&g.warn("Literal date support has been deprecated, please switch to date object usage"),o[b]=new Date(h(a,"medium"))):o[b]=i[b]?l.fromTimezone(new Date(i[b]),q.getOption("timezone")):null,o.refreshView()});break;case"maxMode":case"minMode":a.datepickerOptions[b]?a.$watch(function(){return a.datepickerOptions[b]},function(c){o[b]=a[b]=angular.isDefined(c)?c:a.datepickerOptions[b],("minMode"===b&&o.modes.indexOf(a.datepickerOptions.datepickerMode)o.modes.indexOf(o[b]))&&(a.datepickerMode=o[b],a.datepickerOptions.datepickerMode=o[b])}):o[b]=a[b]=i[b]||null}}),a.uniqueId="datepicker-"+a.$id+"-"+Math.floor(1e4*Math.random()),a.disabled=angular.isDefined(c.disabled)||!1,angular.isDefined(c.ngDisabled)&&r.push(a.$parent.$watch(c.ngDisabled,function(b){a.disabled=b,o.refreshView()})),a.isActive=function(b){return 0===o.compare(b.date,o.activeDate)?(a.activeDateId=b.uid,!0):!1},this.init=function(b){p=b,q=n(p),a.datepickerOptions.initDate?(o.activeDate=l.fromTimezone(a.datepickerOptions.initDate,q.getOption("timezone"))||new Date,a.$watch("datepickerOptions.initDate",function(a){a&&(p.$isEmpty(p.$modelValue)||p.$invalid)&&(o.activeDate=l.fromTimezone(a,q.getOption("timezone")),o.refreshView())})):o.activeDate=new Date;var c=p.$modelValue?new Date(p.$modelValue):new Date;this.activeDate=isNaN(c)?l.fromTimezone(new Date,q.getOption("timezone")):l.fromTimezone(c,q.getOption("timezone")),p.$render=function(){o.render()}},this.render=function(){if(p.$viewValue){var a=new Date(p.$viewValue),b=!isNaN(a);b?this.activeDate=l.fromTimezone(a,q.getOption("timezone")):k||g.error('Datepicker directive: "ng-model" value must be a Date object')}this.refreshView()},this.refreshView=function(){if(this.element){a.selectedDt=null,this._refreshView(),a.activeDt&&(a.activeDateId=a.activeDt.uid);var b=p.$viewValue?new Date(p.$viewValue):null;b=l.fromTimezone(b,q.getOption("timezone")),p.$setValidity("dateDisabled",!b||this.element&&!this.isDisabled(b))}},this.createDateObject=function(b,c){var d=p.$viewValue?new Date(p.$viewValue):null;d=l.fromTimezone(d,q.getOption("timezone"));var e=new Date;e=l.fromTimezone(e,q.getOption("timezone"));var f=this.compare(b,e),g={date:b,label:l.filter(b,c),selected:d&&0===this.compare(b,d),disabled:this.isDisabled(b),past:0>f,current:0===f,future:f>0,customClass:this.customClass(b)||null};return d&&0===this.compare(b,d)&&(a.selectedDt=g),o.activeDate&&0===this.compare(g.date,o.activeDate)&&(a.activeDt=g),g},this.isDisabled=function(b){return a.disabled||this.minDate&&this.compare(b,this.minDate)<0||this.maxDate&&this.compare(b,this.maxDate)>0||a.dateDisabled&&a.dateDisabled({date:b,mode:a.datepickerMode})},this.customClass=function(b){return a.customClass({date:b,mode:a.datepickerMode})},this.split=function(a,b){for(var c=[];a.length>0;)c.push(a.splice(0,b));return c},a.select=function(b){if(a.datepickerMode===o.minMode){var c=p.$viewValue?l.fromTimezone(new Date(p.$viewValue),q.getOption("timezone")):new Date(0,0,0,0,0,0,0);c.setFullYear(b.getFullYear(),b.getMonth(),b.getDate()),c=l.toTimezone(c,q.getOption("timezone")),p.$setViewValue(c),p.$render()}else o.activeDate=b,m(o.modes[o.modes.indexOf(a.datepickerMode)-1]),a.$emit("uib:datepicker.mode");a.$broadcast("uib:datepicker.focus")},a.move=function(a){var b=o.activeDate.getFullYear()+a*(o.step.years||0),c=o.activeDate.getMonth()+a*(o.step.months||0);o.activeDate.setFullYear(b,c,1),o.refreshView()},a.toggleMode=function(b){b=b||1,a.datepickerMode===o.maxMode&&1===b||a.datepickerMode===o.minMode&&-1===b||(m(o.modes[o.modes.indexOf(a.datepickerMode)+b]),a.$emit("uib:datepicker.mode"))},a.keys={13:"enter",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down"};var s=function(){o.element[0].focus()};a.$on("uib:datepicker.focus",s),a.keydown=function(b){var c=a.keys[b.which];if(c&&!b.shiftKey&&!b.altKey&&!a.disabled)if(b.preventDefault(),o.shortcutPropagation||b.stopPropagation(),"enter"===c||"space"===c){if(o.isDisabled(o.activeDate))return;a.select(o.activeDate)}else!b.ctrlKey||"up"!==c&&"down"!==c?(o.handleKeyDown(c,b),o.refreshView()):a.toggleMode("up"===c?1:-1)},b.on("keydown",function(b){a.$apply(function(){a.keydown(b)})}),a.$on("$destroy",function(){for(;r.length;)r.shift()()})}]).controller("UibDaypickerController",["$scope","$element","dateFilter",function(a,b,c){function d(a,b){return 1!==b||a%4!==0||a%100===0&&a%400!==0?f[b]:29}function e(a){var b=new Date(a);b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1}var f=[31,28,31,30,31,30,31,31,30,31,30,31];this.step={months:1},this.element=b,this.init=function(b){angular.extend(b,this),a.showWeeks=b.showWeeks,b.refreshView()},this.getDates=function(a,b){for(var c,d=new Array(b),e=new Date(a),f=0;b>f;)c=new Date(e),d[f++]=c,e.setDate(e.getDate()+1);return d},this._refreshView=function(){var b=this.activeDate.getFullYear(),d=this.activeDate.getMonth(),f=new Date(this.activeDate);f.setFullYear(b,d,1);var g=this.startingDay-f.getDay(),h=g>0?7-g:-g,i=new Date(f);h>0&&i.setDate(-h+1);for(var j=this.getDates(i,42),k=0;42>k;k++)j[k]=angular.extend(this.createDateObject(j[k],this.formatDay),{secondary:j[k].getMonth()!==d,uid:a.uniqueId+"-"+k});a.labels=new Array(7);for(var l=0;7>l;l++)a.labels[l]={abbr:c(j[l].date,this.formatDayHeader),full:c(j[l].date,"EEEE")};if(a.title=c(this.activeDate,this.formatDayTitle),a.rows=this.split(j,7),a.showWeeks){a.weekNumbers=[];for(var m=(11-this.startingDay)%7,n=a.rows.length,o=0;n>o;o++)a.weekNumbers.push(e(a.rows[o][m].date))}},this.compare=function(a,b){var c=new Date(a.getFullYear(),a.getMonth(),a.getDate()),d=new Date(b.getFullYear(),b.getMonth(),b.getDate());return c.setFullYear(a.getFullYear()),d.setFullYear(b.getFullYear()),c-d},this.handleKeyDown=function(a,b){var c=this.activeDate.getDate();if("left"===a)c-=1;else if("up"===a)c-=7;else if("right"===a)c+=1;else if("down"===a)c+=7;else if("pageup"===a||"pagedown"===a){var e=this.activeDate.getMonth()+("pageup"===a?-1:1);this.activeDate.setMonth(e,1),c=Math.min(d(this.activeDate.getFullYear(),this.activeDate.getMonth()),c)}else"home"===a?c=1:"end"===a&&(c=d(this.activeDate.getFullYear(),this.activeDate.getMonth()));this.activeDate.setDate(c)}}]).controller("UibMonthpickerController",["$scope","$element","dateFilter",function(a,b,c){this.step={years:1},this.element=b,this.init=function(a){angular.extend(a,this),a.refreshView()},this._refreshView=function(){for(var b,d=new Array(12),e=this.activeDate.getFullYear(),f=0;12>f;f++)b=new Date(this.activeDate),b.setFullYear(e,f,1),d[f]=angular.extend(this.createDateObject(b,this.formatMonth),{uid:a.uniqueId+"-"+f});a.title=c(this.activeDate,this.formatMonthTitle),a.rows=this.split(d,this.monthColumns),a.yearHeaderColspan=this.monthColumns>3?this.monthColumns-2:1},this.compare=function(a,b){var c=new Date(a.getFullYear(),a.getMonth()),d=new Date(b.getFullYear(),b.getMonth());return c.setFullYear(a.getFullYear()),d.setFullYear(b.getFullYear()),c-d},this.handleKeyDown=function(a,b){var c=this.activeDate.getMonth();if("left"===a)c-=1;else if("up"===a)c-=this.monthColumns;else if("right"===a)c+=1;else if("down"===a)c+=this.monthColumns;else if("pageup"===a||"pagedown"===a){var d=this.activeDate.getFullYear()+("pageup"===a?-1:1);this.activeDate.setFullYear(d)}else"home"===a?c=0:"end"===a&&(c=11);this.activeDate.setMonth(c)}}]).controller("UibYearpickerController",["$scope","$element","dateFilter",function(a,b,c){function d(a){return parseInt((a-1)/f,10)*f+1}var e,f;this.element=b,this.yearpickerInit=function(){e=this.yearColumns,f=this.yearRows*e,this.step={years:f}},this._refreshView=function(){for(var b,c=new Array(f),g=0,h=d(this.activeDate.getFullYear());f>g;g++)b=new Date(this.activeDate),b.setFullYear(h+g,0,1),c[g]=angular.extend(this.createDateObject(b,this.formatYear),{uid:a.uniqueId+"-"+g});a.title=[c[0].label,c[f-1].label].join(" - "),a.rows=this.split(c,e),a.columns=e},this.compare=function(a,b){return a.getFullYear()-b.getFullYear()},this.handleKeyDown=function(a,b){var c=this.activeDate.getFullYear();"left"===a?c-=1:"up"===a?c-=e:"right"===a?c+=1:"down"===a?c+=e:"pageup"===a||"pagedown"===a?c+=("pageup"===a?-1:1)*f:"home"===a?c=d(this.activeDate.getFullYear()):"end"===a&&(c=d(this.activeDate.getFullYear())+f-1),this.activeDate.setFullYear(c)}}]).directive("uibDatepicker",function(){return{templateUrl:function(a,b){return b.templateUrl||"uib/template/datepicker/datepicker.html"},scope:{datepickerOptions:"=?"},require:["uibDatepicker","^ngModel"],restrict:"A",controller:"UibDatepickerController",controllerAs:"datepicker",link:function(a,b,c,d){var e=d[0],f=d[1];e.init(f)}}}).directive("uibDaypicker",function(){return{templateUrl:function(a,b){return b.templateUrl||"uib/template/datepicker/day.html"}, +require:["^uibDatepicker","uibDaypicker"],restrict:"A",controller:"UibDaypickerController",link:function(a,b,c,d){var e=d[0],f=d[1];f.init(e)}}}).directive("uibMonthpicker",function(){return{templateUrl:function(a,b){return b.templateUrl||"uib/template/datepicker/month.html"},require:["^uibDatepicker","uibMonthpicker"],restrict:"A",controller:"UibMonthpickerController",link:function(a,b,c,d){var e=d[0],f=d[1];f.init(e)}}}).directive("uibYearpicker",function(){return{templateUrl:function(a,b){return b.templateUrl||"uib/template/datepicker/year.html"},require:["^uibDatepicker","uibYearpicker"],restrict:"A",controller:"UibYearpickerController",link:function(a,b,c,d){var e=d[0];angular.extend(e,d[1]),e.yearpickerInit(),e.refreshView()}}}),angular.module("ui.bootstrap.position",[]).factory("$uibPosition",["$document","$window",function(a,b){var c,d,e={normal:/(auto|scroll)/,hidden:/(auto|scroll|hidden)/},f={auto:/\s?auto?\s?/i,primary:/^(top|bottom|left|right)$/,secondary:/^(top|bottom|left|right|center)$/,vertical:/^(top|bottom)$/},g=/(HTML|BODY)/;return{getRawNode:function(a){return a.nodeName?a:a[0]||a},parseStyle:function(a){return a=parseFloat(a),isFinite(a)?a:0},offsetParent:function(c){function d(a){return"static"===(b.getComputedStyle(a).position||"static")}c=this.getRawNode(c);for(var e=c.offsetParent||a[0].documentElement;e&&e!==a[0].documentElement&&d(e);)e=e.offsetParent;return e||a[0].documentElement},scrollbarWidth:function(e){if(e){if(angular.isUndefined(d)){var f=a.find("body");f.addClass("uib-position-body-scrollbar-measure"),d=b.innerWidth-f[0].clientWidth,d=isFinite(d)?d:0,f.removeClass("uib-position-body-scrollbar-measure")}return d}if(angular.isUndefined(c)){var g=angular.element('
');a.find("body").append(g),c=g[0].offsetWidth-g[0].clientWidth,c=isFinite(c)?c:0,g.remove()}return c},scrollbarPadding:function(a){a=this.getRawNode(a);var c=b.getComputedStyle(a),d=this.parseStyle(c.paddingRight),e=this.parseStyle(c.paddingBottom),f=this.scrollParent(a,!1,!0),h=this.scrollbarWidth(g.test(f.tagName));return{scrollbarWidth:h,widthOverflow:f.scrollWidth>f.clientWidth,right:d+h,originalRight:d,heightOverflow:f.scrollHeight>f.clientHeight,bottom:e+h,originalBottom:e}},isScrollable:function(a,c){a=this.getRawNode(a);var d=c?e.hidden:e.normal,f=b.getComputedStyle(a);return d.test(f.overflow+f.overflowY+f.overflowX)},scrollParent:function(c,d,f){c=this.getRawNode(c);var g=d?e.hidden:e.normal,h=a[0].documentElement,i=b.getComputedStyle(c);if(f&&g.test(i.overflow+i.overflowY+i.overflowX))return c;var j="absolute"===i.position,k=c.parentElement||h;if(k===h||"fixed"===i.position)return h;for(;k.parentElement&&k!==h;){var l=b.getComputedStyle(k);if(j&&"static"!==l.position&&(j=!1),!j&&g.test(l.overflow+l.overflowY+l.overflowX))break;k=k.parentElement}return k},position:function(c,d){c=this.getRawNode(c);var e=this.offset(c);if(d){var f=b.getComputedStyle(c);e.top-=this.parseStyle(f.marginTop),e.left-=this.parseStyle(f.marginLeft)}var g=this.offsetParent(c),h={top:0,left:0};return g!==a[0].documentElement&&(h=this.offset(g),h.top+=g.clientTop-g.scrollTop,h.left+=g.clientLeft-g.scrollLeft),{width:Math.round(angular.isNumber(e.width)?e.width:c.offsetWidth),height:Math.round(angular.isNumber(e.height)?e.height:c.offsetHeight),top:Math.round(e.top-h.top),left:Math.round(e.left-h.left)}},offset:function(c){c=this.getRawNode(c);var d=c.getBoundingClientRect();return{width:Math.round(angular.isNumber(d.width)?d.width:c.offsetWidth),height:Math.round(angular.isNumber(d.height)?d.height:c.offsetHeight),top:Math.round(d.top+(b.pageYOffset||a[0].documentElement.scrollTop)),left:Math.round(d.left+(b.pageXOffset||a[0].documentElement.scrollLeft))}},viewportOffset:function(c,d,e){c=this.getRawNode(c),e=e!==!1;var f=c.getBoundingClientRect(),g={top:0,left:0,bottom:0,right:0},h=d?a[0].documentElement:this.scrollParent(c),i=h.getBoundingClientRect();if(g.top=i.top+h.clientTop,g.left=i.left+h.clientLeft,h===a[0].documentElement&&(g.top+=b.pageYOffset,g.left+=b.pageXOffset),g.bottom=g.top+h.clientHeight,g.right=g.left+h.clientWidth,e){var j=b.getComputedStyle(h);g.top+=this.parseStyle(j.paddingTop),g.bottom-=this.parseStyle(j.paddingBottom),g.left+=this.parseStyle(j.paddingLeft),g.right-=this.parseStyle(j.paddingRight)}return{top:Math.round(f.top-g.top),bottom:Math.round(g.bottom-f.bottom),left:Math.round(f.left-g.left),right:Math.round(g.right-f.right)}},parsePlacement:function(a){var b=f.auto.test(a);return b&&(a=a.replace(f.auto,"")),a=a.split("-"),a[0]=a[0]||"top",f.primary.test(a[0])||(a[0]="top"),a[1]=a[1]||"center",f.secondary.test(a[1])||(a[1]="center"),b?a[2]=!0:a[2]=!1,a},positionElements:function(a,c,d,e){a=this.getRawNode(a),c=this.getRawNode(c);var g=angular.isDefined(c.offsetWidth)?c.offsetWidth:c.prop("offsetWidth"),h=angular.isDefined(c.offsetHeight)?c.offsetHeight:c.prop("offsetHeight");d=this.parsePlacement(d);var i=e?this.offset(a):this.position(a),j={top:0,left:0,placement:""};if(d[2]){var k=this.viewportOffset(a,e),l=b.getComputedStyle(c),m={width:g+Math.round(Math.abs(this.parseStyle(l.marginLeft)+this.parseStyle(l.marginRight))),height:h+Math.round(Math.abs(this.parseStyle(l.marginTop)+this.parseStyle(l.marginBottom)))};if(d[0]="top"===d[0]&&m.height>k.top&&m.height<=k.bottom?"bottom":"bottom"===d[0]&&m.height>k.bottom&&m.height<=k.top?"top":"left"===d[0]&&m.width>k.left&&m.width<=k.right?"right":"right"===d[0]&&m.width>k.right&&m.width<=k.left?"left":d[0],d[1]="top"===d[1]&&m.height-i.height>k.bottom&&m.height-i.height<=k.top?"bottom":"bottom"===d[1]&&m.height-i.height>k.top&&m.height-i.height<=k.bottom?"top":"left"===d[1]&&m.width-i.width>k.right&&m.width-i.width<=k.left?"right":"right"===d[1]&&m.width-i.width>k.left&&m.width-i.width<=k.right?"left":d[1],"center"===d[1])if(f.vertical.test(d[0])){var n=i.width/2-g/2;k.left+n<0&&m.width-i.width<=k.right?d[1]="left":k.right+n<0&&m.width-i.width<=k.left&&(d[1]="right")}else{var o=i.height/2-m.height/2;k.top+o<0&&m.height-i.height<=k.bottom?d[1]="top":k.bottom+o<0&&m.height-i.height<=k.top&&(d[1]="bottom")}}switch(d[0]){case"top":j.top=i.top-h;break;case"bottom":j.top=i.top+i.height;break;case"left":j.left=i.left-g;break;case"right":j.left=i.left+i.width}switch(d[1]){case"top":j.top=i.top;break;case"bottom":j.top=i.top+i.height-h;break;case"left":j.left=i.left;break;case"right":j.left=i.left+i.width-g;break;case"center":f.vertical.test(d[0])?j.left=i.left+i.width/2-g/2:j.top=i.top+i.height/2-h/2}return j.top=Math.round(j.top),j.left=Math.round(j.left),j.placement="center"===d[1]?d[0]:d[0]+"-"+d[1],j},adjustTop:function(a,b,c,d){return-1!==a.indexOf("top")&&c!==d?{top:b.top-d+"px"}:void 0},positionArrow:function(a,c){a=this.getRawNode(a);var d=a.querySelector(".tooltip-inner, .popover-inner");if(d){var e=angular.element(d).hasClass("tooltip-inner"),g=e?a.querySelector(".tooltip-arrow"):a.querySelector(".arrow");if(g){var h={top:"",bottom:"",left:"",right:""};if(c=this.parsePlacement(c),"center"===c[1])return void angular.element(g).css(h);var i="border-"+c[0]+"-width",j=b.getComputedStyle(g)[i],k="border-";k+=f.vertical.test(c[0])?c[0]+"-"+c[1]:c[1]+"-"+c[0],k+="-radius";var l=b.getComputedStyle(e?d:a)[k];switch(c[0]){case"top":h.bottom=e?"0":"-"+j;break;case"bottom":h.top=e?"0":"-"+j;break;case"left":h.right=e?"0":"-"+j;break;case"right":h.left=e?"0":"-"+j}h[c[1]]=l,angular.element(g).css(h)}}}}}]),angular.module("ui.bootstrap.datepickerPopup",["ui.bootstrap.datepicker","ui.bootstrap.position"]).value("$datepickerPopupLiteralWarning",!0).constant("uibDatepickerPopupConfig",{altInputFormats:[],appendToBody:!1,clearText:"Clear",closeOnDateSelection:!0,closeText:"Done",currentText:"Today",datepickerPopup:"yyyy-MM-dd",datepickerPopupTemplateUrl:"uib/template/datepickerPopup/popup.html",datepickerTemplateUrl:"uib/template/datepicker/datepicker.html",html5Types:{date:"yyyy-MM-dd","datetime-local":"yyyy-MM-ddTHH:mm:ss.sss",month:"yyyy-MM"},onOpenFocus:!0,showButtonBar:!0,placement:"auto bottom-left"}).controller("UibDatepickerPopupController",["$scope","$element","$attrs","$compile","$log","$parse","$window","$document","$rootScope","$uibPosition","dateFilter","uibDateParser","uibDatepickerPopupConfig","$timeout","uibDatepickerConfig","$datepickerPopupLiteralWarning",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){function q(b){var c=l.parse(b,x,a.date);if(isNaN(c))for(var d=0;d
"),D.attr({"ng-model":"date","ng-change":"dateSelection(date)","template-url":B}),E=angular.element(D.children()[0]),E.attr("template-url",C),a.datepickerOptions||(a.datepickerOptions={}),K&&"month"===c.type&&(a.datepickerOptions.datepickerMode="month",a.datepickerOptions.minMode="month"),E.attr("datepicker-options","datepickerOptions"),K?G.$formatters.push(function(b){return a.date=l.fromTimezone(b,H.getOption("timezone")),b}):(G.$$parserName="date",G.$validators.date=s,G.$parsers.unshift(r),G.$formatters.push(function(b){return G.$isEmpty(b)?(a.date=b,b):(angular.isNumber(b)&&(b=new Date(b)),a.date=l.fromTimezone(b,H.getOption("timezone")),l.filter(a.date,x))})),G.$viewChangeListeners.push(function(){a.date=q(G.$viewValue)}),b.on("keydown",u),I=d(D)(a),D.remove(),z?h.find("body").append(I):b.after(I),a.$on("$destroy",function(){for(a.isOpen===!0&&(i.$$phase||a.$apply(function(){a.isOpen=!1})),I.remove(),b.off("keydown",u),h.off("click",t),F&&F.off("scroll",v),angular.element(g).off("resize",v);L.length;)L.shift()()})},a.getText=function(b){return a[b+"Text"]||m[b+"Text"]},a.isDisabled=function(b){"today"===b&&(b=l.fromTimezone(new Date,H.getOption("timezone")));var c={};return angular.forEach(["minDate","maxDate"],function(b){a.datepickerOptions[b]?angular.isDate(a.datepickerOptions[b])?c[b]=new Date(a.datepickerOptions[b]):(p&&e.warn("Literal date support has been deprecated, please switch to date object usage"),c[b]=new Date(k(a.datepickerOptions[b],"medium"))):c[b]=null}),a.datepickerOptions&&c.minDate&&a.compare(b,c.minDate)<0||c.maxDate&&a.compare(b,c.maxDate)>0},a.compare=function(a,b){return new Date(a.getFullYear(),a.getMonth(),a.getDate())-new Date(b.getFullYear(),b.getMonth(),b.getDate())},a.dateSelection=function(c){a.date=c;var d=a.date?l.filter(a.date,x):null;b.val(d),G.$setViewValue(d),y&&(a.isOpen=!1,b[0].focus())},a.keydown=function(c){27===c.which&&(c.stopPropagation(),a.isOpen=!1,b[0].focus())},a.select=function(b,c){if(c.stopPropagation(),"today"===b){var d=new Date;angular.isDate(a.date)?(b=new Date(a.date),b.setFullYear(d.getFullYear(),d.getMonth(),d.getDate())):(b=l.fromTimezone(d,H.getOption("timezone")),b.setHours(0,0,0,0))}a.dateSelection(b)},a.close=function(c){c.stopPropagation(),a.isOpen=!1,b[0].focus()},a.disabled=angular.isDefined(c.disabled)||!1,c.ngDisabled&&L.push(a.$parent.$watch(f(c.ngDisabled),function(b){a.disabled=b})),a.$watch("isOpen",function(d){d?a.disabled?a.isOpen=!1:n(function(){v(),A&&a.$broadcast("uib:datepicker.focus"),h.on("click",t);var d=c.popupPlacement?c.popupPlacement:m.placement;z||j.parsePlacement(d)[2]?(F=F||angular.element(j.scrollParent(b)),F&&F.on("scroll",v)):F=null,angular.element(g).on("resize",v)},0,!1):(h.off("click",t),F&&F.off("scroll",v),angular.element(g).off("resize",v))}),a.$on("uib:datepicker.mode",function(){n(v,0,!1)})}]).directive("uibDatepickerPopup",function(){return{require:["ngModel","uibDatepickerPopup"],controller:"UibDatepickerPopupController",scope:{datepickerOptions:"=?",isOpen:"=?",currentText:"@",clearText:"@",closeText:"@"},link:function(a,b,c,d){var e=d[0],f=d[1];f.init(e)}}}).directive("uibDatepickerPopupWrap",function(){return{restrict:"A",transclude:!0,templateUrl:function(a,b){return b.templateUrl||"uib/template/datepickerPopup/popup.html"}}}),angular.module("ui.bootstrap.debounce",[]).factory("$$debounce",["$timeout",function(a){return function(b,c){var d;return function(){var e=this,f=Array.prototype.slice.call(arguments);d&&a.cancel(d),d=a(function(){b.apply(e,f)},c)}}}]),angular.module("ui.bootstrap.multiMap",[]).factory("$$multiMap",function(){return{createNew:function(){var a={};return{entries:function(){return Object.keys(a).map(function(b){return{key:b,value:a[b]}})},get:function(b){return a[b]},hasKey:function(b){return!!a[b]},keys:function(){return Object.keys(a)},put:function(b,c){a[b]||(a[b]=[]),a[b].push(c)},remove:function(b,c){var d=a[b];if(d){var e=d.indexOf(c);-1!==e&&d.splice(e,1),d.length||delete a[b]}}}}}}),angular.module("ui.bootstrap.dropdown",["ui.bootstrap.multiMap","ui.bootstrap.position"]).constant("uibDropdownConfig",{appendToOpenClass:"uib-dropdown-open",openClass:"open"}).service("uibDropdownService",["$document","$rootScope","$$multiMap",function(a,b,c){var d=null,e=c.createNew();this.isOnlyOpen=function(a,b){var c=e.get(b);if(c){var d=c.reduce(function(b,c){return c.scope===a?c:b},{});if(d)return 1===c.length}return!1},this.open=function(b,c,g){if(d||a.on("click",f),d&&d!==b&&(d.isOpen=!1),d=b,g){var h=e.get(g);if(h){var i=h.map(function(a){return a.scope});-1===i.indexOf(b)&&e.put(g,{scope:b})}else e.put(g,{scope:b})}},this.close=function(b,c,g){if(d===b&&(a.off("click",f),a.off("keydown",this.keybindFilter),d=null),g){var h=e.get(g);if(h){var i=h.reduce(function(a,c){return c.scope===b?c:a},{});i&&e.remove(g,i)}}};var f=function(a){if(d&&d.isOpen&&!(a&&"disabled"===d.getAutoClose()||a&&3===a.which)){var c=d.getToggleElement();if(!(a&&c&&c[0].contains(a.target))){var e=d.getDropdownElement();a&&"outsideClick"===d.getAutoClose()&&e&&e[0].contains(a.target)||(d.focusToggleElement(),d.isOpen=!1,b.$$phase||d.$apply())}}};this.keybindFilter=function(a){if(d){var b=d.getDropdownElement(),c=d.getToggleElement(),e=b&&b[0].contains(a.target),g=c&&c[0].contains(a.target);27===a.which?(a.stopPropagation(),d.focusToggleElement(),f()):d.isKeynavEnabled()&&-1!==[38,40].indexOf(a.which)&&d.isOpen&&(e||g)&&(a.preventDefault(),a.stopPropagation(),d.focusDropdownEntry(a.which))}}}]).controller("UibDropdownController",["$scope","$element","$attrs","$parse","uibDropdownConfig","uibDropdownService","$animate","$uibPosition","$document","$compile","$templateRequest",function(a,b,c,d,e,f,g,h,i,j,k){function l(){b.append(o.dropdownMenu)}var m,n,o=this,p=a.$new(),q=e.appendToOpenClass,r=e.openClass,s=angular.noop,t=c.onToggle?d(c.onToggle):angular.noop,u=!1,v=i.find("body");b.addClass("dropdown"),this.init=function(){c.isOpen&&(n=d(c.isOpen),s=n.assign,a.$watch(n,function(a){p.isOpen=!!a})),u=angular.isDefined(c.keyboardNav)},this.toggle=function(a){return p.isOpen=arguments.length?!!a:!p.isOpen,angular.isFunction(s)&&s(p,p.isOpen),p.isOpen},this.isOpen=function(){return p.isOpen},p.getToggleElement=function(){return o.toggleElement},p.getAutoClose=function(){return c.autoClose||"always"},p.getElement=function(){return b},p.isKeynavEnabled=function(){return u},p.focusDropdownEntry=function(a){var c=o.dropdownMenu?angular.element(o.dropdownMenu).find("a"):b.find("ul").eq(0).find("a");switch(a){case 40:angular.isNumber(o.selectedOption)?o.selectedOption=o.selectedOption===c.length-1?o.selectedOption:o.selectedOption+1:o.selectedOption=0;break;case 38:angular.isNumber(o.selectedOption)?o.selectedOption=0===o.selectedOption?0:o.selectedOption-1:o.selectedOption=c.length-1}c[o.selectedOption].focus()},p.getDropdownElement=function(){return o.dropdownMenu},p.focusToggleElement=function(){o.toggleElement&&o.toggleElement[0].focus()},p.$watch("isOpen",function(e,n){var u=null,w=!1;if(angular.isDefined(c.dropdownAppendTo)){var x=d(c.dropdownAppendTo)(p);x&&(u=angular.element(x))}if(angular.isDefined(c.dropdownAppendToBody)){var y=d(c.dropdownAppendToBody)(p);y!==!1&&(w=!0)}if(w&&!u&&(u=v),u&&o.dropdownMenu&&(e?(u.append(o.dropdownMenu),b.on("$destroy",l)):(b.off("$destroy",l),l())),u&&o.dropdownMenu){var z,A,B,C=h.positionElements(b,o.dropdownMenu,"bottom-left",!0),D=0;if(z={top:C.top+"px",display:e?"block":"none"},A=o.dropdownMenu.hasClass("dropdown-menu-right"),A?(z.left="auto",B=h.scrollbarPadding(u),B.heightOverflow&&B.scrollbarWidth&&(D=B.scrollbarWidth),z.right=window.innerWidth-D-(C.left+b.prop("offsetWidth"))+"px"):(z.left=C.left+"px",z.right="auto"),!w){var E=h.offset(u);z.top=C.top-E.top+"px",A?z.right=window.innerWidth-(C.left-E.left+b.prop("offsetWidth"))+"px":z.left=C.left-E.left+"px"}o.dropdownMenu.css(z)}var F=u?u:b,G=u?q:r,H=F.hasClass(G),I=f.isOnlyOpen(a,u);if(H===!e){var J;J=u?I?"removeClass":"addClass":e?"addClass":"removeClass",g[J](F,G).then(function(){angular.isDefined(e)&&e!==n&&t(a,{open:!!e})})}if(e)o.dropdownMenuTemplateUrl?k(o.dropdownMenuTemplateUrl).then(function(a){m=p.$new(),j(a.trim())(m,function(a){var b=a;o.dropdownMenu.replaceWith(b),o.dropdownMenu=b,i.on("keydown",f.keybindFilter)})}):i.on("keydown",f.keybindFilter),p.focusToggleElement(),f.open(p,b,u);else{if(f.close(p,b,u),o.dropdownMenuTemplateUrl){m&&m.$destroy();var K=angular.element('');o.dropdownMenu.replaceWith(K),o.dropdownMenu=K}o.selectedOption=null}angular.isFunction(s)&&s(a,e)})}]).directive("uibDropdown",function(){return{controller:"UibDropdownController",link:function(a,b,c,d){d.init()}}}).directive("uibDropdownMenu",function(){return{restrict:"A",require:"?^uibDropdown",link:function(a,b,c,d){if(d&&!angular.isDefined(c.dropdownNested)){b.addClass("dropdown-menu");var e=c.templateUrl;e&&(d.dropdownMenuTemplateUrl=e),d.dropdownMenu||(d.dropdownMenu=b)}}}}).directive("uibDropdownToggle",function(){return{require:"?^uibDropdown",link:function(a,b,c,d){if(d){b.addClass("dropdown-toggle"),d.toggleElement=b;var e=function(e){e.preventDefault(),b.hasClass("disabled")||c.disabled||a.$apply(function(){d.toggle()})};b.on("click",e),b.attr({"aria-haspopup":!0,"aria-expanded":!1}),a.$watch(d.isOpen,function(a){b.attr("aria-expanded",!!a)}),a.$on("$destroy",function(){b.off("click",e)})}}}}),angular.module("ui.bootstrap.stackedMap",[]).factory("$$stackedMap",function(){return{createNew:function(){var a=[];return{add:function(b,c){a.push({key:b,value:c})},get:function(b){for(var c=0;c-1&&A>a&&(a=A),a}function m(a,b){var c=x.get(a).value,d=c.appendTo;x.remove(a),B=x.top(),B&&(A=parseInt(B.value.modalDomEl.attr("index"),10)),p(c.modalDomEl,c.modalScope,function(){var b=c.openedClass||w;y.remove(b,a);var e=y.hasKey(b);d.toggleClass(b,e),!e&&v&&v.heightOverflow&&v.scrollbarWidth&&(v.originalRight?d.css({paddingRight:v.originalRight+"px"}):d.css({paddingRight:""}),v=null),n(!0)},c.closedDeferred),o(),b&&b.focus?b.focus():d.focus&&d.focus()}function n(a){var b;x.length()>0&&(b=x.top().value,b.modalDomEl.toggleClass(b.windowTopClass||"",a))}function o(){if(t&&-1===l()){var a=u;p(t,u,function(){a=null}),t=void 0,u=void 0}}function p(b,c,d,e){function g(){g.done||(g.done=!0,a.leave(b).then(function(){d&&d(),b.remove(),e&&e.resolve()}),c.$destroy())}var h,i=null,j=function(){return h||(h=f.defer(),i=h.promise),function(){h.resolve()}};return c.$broadcast(z.NOW_CLOSING_EVENT,j),f.when(i).then(g)}function q(a){if(a.isDefaultPrevented())return a;var b=x.top();if(b)switch(a.which){case 27:b.value.keyboard&&(a.preventDefault(),e.$apply(function(){z.dismiss(b.key,"escape key press")}));break;case 9:var c=z.loadFocusElementList(b),d=!1;a.shiftKey?(z.isFocusInFirstItem(a,c)||z.isModalFocused(a,b))&&(d=z.focusLastFocusableElement(c)):z.isFocusInLastItem(a,c)&&(d=z.focusFirstFocusableElement(c)),d&&(a.preventDefault(),a.stopPropagation())}}function r(a,b,c){return!a.value.modalScope.$broadcast("modal.closing",b,c).defaultPrevented}function s(){Array.prototype.forEach.call(document.querySelectorAll("["+C+"]"),function(a){var b=parseInt(a.getAttribute(C),10),c=b-1;a.setAttribute(C,c),c||(a.removeAttribute(C),a.removeAttribute("aria-hidden"))})}var t,u,v,w="modal-open",x=h.createNew(),y=g.createNew(),z={NOW_CLOSING_EVENT:"modal.stack.now-closing"},A=0,B=null,C="data-bootstrap-modal-aria-hidden-count",D="a[href], area[href], input:not([disabled]):not([tabindex='-1']), button:not([disabled]):not([tabindex='-1']),select:not([disabled]):not([tabindex='-1']), textarea:not([disabled]):not([tabindex='-1']), iframe, object, embed, *[tabindex]:not([tabindex='-1']), *[contenteditable=true]",E=/[A-Z]/g;return e.$watch(l,function(a){u&&(u.index=a)}),c.on("keydown",q),e.$on("$destroy",function(){c.off("keydown",q)}),z.open=function(b,f){function g(a){function b(a){var b=a.parent()?a.parent().children():[];return Array.prototype.filter.call(b,function(b){return b!==a[0]})}if(a&&"BODY"!==a[0].tagName)return b(a).forEach(function(a){var b="true"===a.getAttribute("aria-hidden"),c=parseInt(a.getAttribute(C),10);c||(c=b?1:0),a.setAttribute(C,c+1),a.setAttribute("aria-hidden","true")}),g(a.parent())}var h=c[0].activeElement,k=f.openedClass||w;n(!1),B=x.top(),x.add(b,{deferred:f.deferred,renderDeferred:f.renderDeferred,closedDeferred:f.closedDeferred,modalScope:f.scope,backdrop:f.backdrop,keyboard:f.keyboard,openedClass:f.openedClass,windowTopClass:f.windowTopClass,animation:f.animation,appendTo:f.appendTo}),y.put(k,b);var m=f.appendTo,o=l();o>=0&&!t&&(u=e.$new(!0),u.modalOptions=f,u.index=o,t=angular.element('
'),t.attr({"class":"modal-backdrop","ng-style":"{'z-index': 1040 + (index && 1 || 0) + index*10}","uib-modal-animation-class":"fade","modal-in-class":"in"}),f.backdropClass&&t.addClass(f.backdropClass),f.animation&&t.attr("modal-animation","true"),d(t)(u),a.enter(t,m),i.isScrollable(m)&&(v=i.scrollbarPadding(m),v.heightOverflow&&v.scrollbarWidth&&m.css({paddingRight:v.right+"px"})));var p;f.component?(p=document.createElement(j(f.component.name)),p=angular.element(p),p.attr({resolve:"$resolve","modal-instance":"$uibModalInstance",close:"$close($value)",dismiss:"$dismiss($value)"})):p=f.content,A=B?parseInt(B.value.modalDomEl.attr("index"),10)+1:0;var q=angular.element('
');q.attr({"class":"modal","template-url":f.windowTemplateUrl,"window-top-class":f.windowTopClass,role:"dialog","aria-labelledby":f.ariaLabelledBy,"aria-describedby":f.ariaDescribedBy,size:f.size,index:A,animate:"animate","ng-style":"{'z-index': 1050 + $$topModalIndex*10, display: 'block'}",tabindex:-1,"uib-modal-animation-class":"fade","modal-in-class":"in"}).append(p),f.windowClass&&q.addClass(f.windowClass),f.animation&&q.attr("modal-animation","true"),m.addClass(k),f.scope&&(f.scope.$$topModalIndex=A),a.enter(d(q)(f.scope),m),x.top().value.modalDomEl=q,x.top().value.modalOpener=h,g(q)},z.close=function(a,b){var c=x.get(a);return s(),c&&r(c,b,!0)?(c.value.modalScope.$$uibDestructionScheduled=!0,c.value.deferred.resolve(b),m(a,c.value.modalOpener),!0):!c},z.dismiss=function(a,b){var c=x.get(a);return s(),c&&r(c,b,!1)?(c.value.modalScope.$$uibDestructionScheduled=!0,c.value.deferred.reject(b),m(a,c.value.modalOpener),!0):!c},z.dismissAll=function(a){for(var b=this.getTop();b&&this.dismiss(b.key,a);)b=this.getTop()},z.getTop=function(){return x.top()},z.modalRendered=function(a){var b=x.get(a);b&&b.value.renderDeferred.resolve()},z.focusFirstFocusableElement=function(a){return a.length>0?(a[0].focus(),!0):!1},z.focusLastFocusableElement=function(a){return a.length>0?(a[a.length-1].focus(),!0):!1},z.isModalFocused=function(a,b){if(a&&b){var c=b.value.modalDomEl;if(c&&c.length)return(a.target||a.srcElement)===c[0]}return!1},z.isFocusInFirstItem=function(a,b){return b.length>0?(a.target||a.srcElement)===b[0]:!1},z.isFocusInLastItem=function(a,b){return b.length>0?(a.target||a.srcElement)===b[b.length-1]:!1},z.loadFocusElementList=function(a){if(a){var b=a.value.modalDomEl;if(b&&b.length){var c=b[0].querySelectorAll(D);return c?Array.prototype.filter.call(c,function(a){return k(a)}):c}}},z}]).provider("$uibModal",function(){var a={options:{animation:!0,backdrop:!0,keyboard:!0},$get:["$rootScope","$q","$document","$templateRequest","$controller","$uibResolve","$uibModalStack",function(b,c,d,e,f,g,h){function i(a){return a.template?c.when(a.template):e(angular.isFunction(a.templateUrl)?a.templateUrl():a.templateUrl)}var j={},k=null;return j.getPromiseChain=function(){return k},j.open=function(e){function j(){return q}var l=c.defer(),m=c.defer(),n=c.defer(),o=c.defer(),p={result:l.promise,opened:m.promise,closed:n.promise,rendered:o.promise,close:function(a){return h.close(p,a)},dismiss:function(a){return h.dismiss(p,a)}};if(e=angular.extend({},a.options,e),e.resolve=e.resolve||{},e.appendTo=e.appendTo||d.find("body").eq(0),!e.appendTo.length)throw new Error("appendTo element not found. Make sure that the element passed is in DOM.");if(!e.component&&!e.template&&!e.templateUrl)throw new Error("One of component or template or templateUrl options is required.");var q;q=e.component?c.when(g.resolve(e.resolve,{},null,null)):c.all([i(e),g.resolve(e.resolve,{},null,null)]);var r;return r=k=c.all([k]).then(j,j).then(function(a){function c(b,c,d,e){b.$scope=g,b.$scope.$resolve={},d?b.$scope.$uibModalInstance=p:b.$uibModalInstance=p;var f=c?a[1]:a;angular.forEach(f,function(a,c){e&&(b[c]=a),b.$scope.$resolve[c]=a})}var d=e.scope||b,g=d.$new();g.$close=p.close,g.$dismiss=p.dismiss,g.$on("$destroy",function(){g.$$uibDestructionScheduled||g.$dismiss("$uibUnscheduledDestruction")});var i,j,k={scope:g,deferred:l,renderDeferred:o,closedDeferred:n,animation:e.animation,backdrop:e.backdrop,keyboard:e.keyboard,backdropClass:e.backdropClass,windowTopClass:e.windowTopClass,windowClass:e.windowClass,windowTemplateUrl:e.windowTemplateUrl,ariaLabelledBy:e.ariaLabelledBy,ariaDescribedBy:e.ariaDescribedBy,size:e.size,openedClass:e.openedClass,appendTo:e.appendTo},q={},r={};e.component?(c(q,!1,!0,!1),q.name=e.component,k.component=q):e.controller&&(c(r,!0,!1,!0),j=f(e.controller,r,!0,e.controllerAs),e.controllerAs&&e.bindToController&&(i=j.instance,i.$close=g.$close,i.$dismiss=g.$dismiss,angular.extend(i,{$resolve:r.$scope.$resolve},d)),i=j(),angular.isFunction(i.$onInit)&&i.$onInit()),e.component||(k.content=a[0]),h.open(p,k),m.resolve(!0)},function(a){m.reject(a),l.reject(a)})["finally"](function(){k===r&&(k=null)}),p},j}]};return a}),angular.module("ui.bootstrap.paging",[]).factory("uibPaging",["$parse",function(a){return{create:function(b,c,d){b.setNumPages=d.numPages?a(d.numPages).assign:angular.noop,b.ngModelCtrl={$setViewValue:angular.noop},b._watchers=[],b.init=function(a,e){b.ngModelCtrl=a,b.config=e,a.$render=function(){b.render()},d.itemsPerPage?b._watchers.push(c.$parent.$watch(d.itemsPerPage,function(a){ +b.itemsPerPage=parseInt(a,10),c.totalPages=b.calculateTotalPages(),b.updatePage()})):b.itemsPerPage=e.itemsPerPage,c.$watch("totalItems",function(a,d){(angular.isDefined(a)||a!==d)&&(c.totalPages=b.calculateTotalPages(),b.updatePage())})},b.calculateTotalPages=function(){var a=b.itemsPerPage<1?1:Math.ceil(c.totalItems/b.itemsPerPage);return Math.max(a||0,1)},b.render=function(){c.page=parseInt(b.ngModelCtrl.$viewValue,10)||1},c.selectPage=function(a,d){d&&d.preventDefault();var e=!c.ngDisabled||!d;e&&c.page!==a&&a>0&&a<=c.totalPages&&(d&&d.target&&d.target.blur(),b.ngModelCtrl.$setViewValue(a),b.ngModelCtrl.$render())},c.getText=function(a){return c[a+"Text"]||b.config[a+"Text"]},c.noPrevious=function(){return 1===c.page},c.noNext=function(){return c.page===c.totalPages},b.updatePage=function(){b.setNumPages(c.$parent,c.totalPages),c.page>c.totalPages?c.selectPage(c.totalPages):b.ngModelCtrl.$render()},c.$on("$destroy",function(){for(;b._watchers.length;)b._watchers.shift()()})}}}]),angular.module("ui.bootstrap.pager",["ui.bootstrap.paging","ui.bootstrap.tabindex"]).controller("UibPagerController",["$scope","$attrs","uibPaging","uibPagerConfig",function(a,b,c,d){a.align=angular.isDefined(b.align)?a.$parent.$eval(b.align):d.align,c.create(this,a,b)}]).constant("uibPagerConfig",{itemsPerPage:10,previousText:"« Previous",nextText:"Next »",align:!0}).directive("uibPager",["uibPagerConfig",function(a){return{scope:{totalItems:"=",previousText:"@",nextText:"@",ngDisabled:"="},require:["uibPager","?ngModel"],restrict:"A",controller:"UibPagerController",controllerAs:"pager",templateUrl:function(a,b){return b.templateUrl||"uib/template/pager/pager.html"},link:function(b,c,d,e){c.addClass("pager");var f=e[0],g=e[1];g&&f.init(g,a)}}}]),angular.module("ui.bootstrap.pagination",["ui.bootstrap.paging","ui.bootstrap.tabindex"]).controller("UibPaginationController",["$scope","$attrs","$parse","uibPaging","uibPaginationConfig",function(a,b,c,d,e){function f(a,b,c){return{number:a,text:b,active:c}}function g(a,b){var c=[],d=1,e=b,g=angular.isDefined(i)&&b>i;g&&(j?(d=Math.max(a-Math.floor(i/2),1),e=d+i-1,e>b&&(e=b,d=e-i+1)):(d=(Math.ceil(a/i)-1)*i+1,e=Math.min(d+i-1,b)));for(var h=d;e>=h;h++){var n=f(h,m(h),h===a);c.push(n)}if(g&&i>0&&(!j||k||l)){if(d>1){if(!l||d>3){var o=f(d-1,"...",!1);c.unshift(o)}if(l){if(3===d){var p=f(2,"2",!1);c.unshift(p)}var q=f(1,"1",!1);c.unshift(q)}}if(b>e){if(!l||b-2>e){var r=f(e+1,"...",!1);c.push(r)}if(l){if(e===b-2){var s=f(b-1,b-1,!1);c.push(s)}var t=f(b,b,!1);c.push(t)}}}return c}var h=this,i=angular.isDefined(b.maxSize)?a.$parent.$eval(b.maxSize):e.maxSize,j=angular.isDefined(b.rotate)?a.$parent.$eval(b.rotate):e.rotate,k=angular.isDefined(b.forceEllipses)?a.$parent.$eval(b.forceEllipses):e.forceEllipses,l=angular.isDefined(b.boundaryLinkNumbers)?a.$parent.$eval(b.boundaryLinkNumbers):e.boundaryLinkNumbers,m=angular.isDefined(b.pageLabel)?function(c){return a.$parent.$eval(b.pageLabel,{$page:c})}:angular.identity;a.boundaryLinks=angular.isDefined(b.boundaryLinks)?a.$parent.$eval(b.boundaryLinks):e.boundaryLinks,a.directionLinks=angular.isDefined(b.directionLinks)?a.$parent.$eval(b.directionLinks):e.directionLinks,b.$set("role","menu"),d.create(this,a,b),b.maxSize&&h._watchers.push(a.$parent.$watch(c(b.maxSize),function(a){i=parseInt(a,10),h.render()}));var n=this.render;this.render=function(){n(),a.page>0&&a.page<=a.totalPages&&(a.pages=g(a.page,a.totalPages))}}]).constant("uibPaginationConfig",{itemsPerPage:10,boundaryLinks:!1,boundaryLinkNumbers:!1,directionLinks:!0,firstText:"First",previousText:"Previous",nextText:"Next",lastText:"Last",rotate:!0,forceEllipses:!1}).directive("uibPagination",["$parse","uibPaginationConfig",function(a,b){return{scope:{totalItems:"=",firstText:"@",previousText:"@",nextText:"@",lastText:"@",ngDisabled:"="},require:["uibPagination","?ngModel"],restrict:"A",controller:"UibPaginationController",controllerAs:"pagination",templateUrl:function(a,b){return b.templateUrl||"uib/template/pagination/pagination.html"},link:function(a,c,d,e){c.addClass("pagination");var f=e[0],g=e[1];g&&f.init(g,b)}}}]),angular.module("ui.bootstrap.tooltip",["ui.bootstrap.position","ui.bootstrap.stackedMap"]).provider("$uibTooltip",function(){function a(a){var b=/[A-Z]/g,c="-";return a.replace(b,function(a,b){return(b?c:"")+a.toLowerCase()})}var b={placement:"top",placementClassPrefix:"",animation:!0,popupDelay:0,popupCloseDelay:0,useContentExp:!1},c={mouseenter:"mouseleave",click:"click",outsideClick:"outsideClick",focus:"blur",none:""},d={};this.options=function(a){angular.extend(d,a)},this.setTriggers=function(a){angular.extend(c,a)},this.$get=["$window","$compile","$timeout","$document","$uibPosition","$interpolate","$rootScope","$parse","$$stackedMap",function(e,f,g,h,i,j,k,l,m){function n(a){if(27===a.which){var b=o.top();b&&(b.value.close(),b=null)}}var o=m.createNew();return h.on("keyup",n),k.$on("$destroy",function(){h.off("keyup",n)}),function(e,k,m,n){function p(a){var b=(a||n.trigger||m).split(" "),d=b.map(function(a){return c[a]||a});return{show:b,hide:d}}n=angular.extend({},b,d,n);var q=a(e),r=j.startSymbol(),s=j.endSymbol(),t="
';return{compile:function(a,b){var c=f(t);return function(a,b,d,f){function j(){P.isOpen?q():m()}function m(){O&&!a.$eval(d[k+"Enable"])||(u(),x(),P.popupDelay?H||(H=g(r,P.popupDelay,!1)):r())}function q(){s(),P.popupCloseDelay?I||(I=g(t,P.popupCloseDelay,!1)):t()}function r(){return s(),u(),P.content?(v(),void P.$evalAsync(function(){P.isOpen=!0,y(!0),U()})):angular.noop}function s(){H&&(g.cancel(H),H=null),J&&(g.cancel(J),J=null)}function t(){P&&P.$evalAsync(function(){P&&(P.isOpen=!1,y(!1),P.animation?G||(G=g(w,150,!1)):w())})}function u(){I&&(g.cancel(I),I=null),G&&(g.cancel(G),G=null)}function v(){E||(F=P.$new(),E=c(F,function(a){M?h.find("body").append(a):b.after(a)}),o.add(P,{close:t}),z())}function w(){s(),u(),A(),E&&(E.remove(),E=null,K&&g.cancel(K)),o.remove(P),F&&(F.$destroy(),F=null)}function x(){P.title=d[k+"Title"],S?P.content=S(a):P.content=d[e],P.popupClass=d[k+"Class"],P.placement=angular.isDefined(d[k+"Placement"])?d[k+"Placement"]:n.placement;var b=i.parsePlacement(P.placement);L=b[1]?b[0]+"-"+b[1]:b[0];var c=parseInt(d[k+"PopupDelay"],10),f=parseInt(d[k+"PopupCloseDelay"],10);P.popupDelay=isNaN(c)?n.popupDelay:c,P.popupCloseDelay=isNaN(f)?n.popupCloseDelay:f}function y(b){R&&angular.isFunction(R.assign)&&R.assign(a,b)}function z(){T.length=0,S?(T.push(a.$watch(S,function(a){P.content=a,!a&&P.isOpen&&t()})),T.push(F.$watch(function(){Q||(Q=!0,F.$$postDigest(function(){Q=!1,P&&P.isOpen&&U()}))}))):T.push(d.$observe(e,function(a){P.content=a,!a&&P.isOpen?t():U()})),T.push(d.$observe(k+"Title",function(a){P.title=a,P.isOpen&&U()})),T.push(d.$observe(k+"Placement",function(a){P.placement=a?a:n.placement,P.isOpen&&U()}))}function A(){T.length&&(angular.forEach(T,function(a){a()}),T.length=0)}function B(a){P&&P.isOpen&&E&&(b[0].contains(a.target)||E[0].contains(a.target)||q())}function C(a){27===a.which&&q()}function D(){var c=[],e=[],f=a.$eval(d[k+"Trigger"]);V(),angular.isObject(f)?(Object.keys(f).forEach(function(a){c.push(a),e.push(f[a])}),N={show:c,hide:e}):N=p(f),"none"!==N.show&&N.show.forEach(function(a,c){"outsideClick"===a?(b.on("click",j),h.on("click",B)):a===N.hide[c]?b.on(a,j):a&&(b.on(a,m),b.on(N.hide[c],q)),b.on("keypress",C)})}var E,F,G,H,I,J,K,L,M=angular.isDefined(n.appendToBody)?n.appendToBody:!1,N=p(void 0),O=angular.isDefined(d[k+"Enable"]),P=a.$new(!0),Q=!1,R=angular.isDefined(d[k+"IsOpen"])?l(d[k+"IsOpen"]):!1,S=n.useContentExp?l(d[e]):!1,T=[],U=function(){E&&E.html()&&(J||(J=g(function(){var a=i.positionElements(b,E,P.placement,M),c=angular.isDefined(E.offsetHeight)?E.offsetHeight:E.prop("offsetHeight"),d=M?i.offset(b):i.position(b);E.css({top:a.top+"px",left:a.left+"px"});var e=a.placement.split("-");E.hasClass(e[0])||(E.removeClass(L.split("-")[0]),E.addClass(e[0])),E.hasClass(n.placementClassPrefix+a.placement)||(E.removeClass(n.placementClassPrefix+L),E.addClass(n.placementClassPrefix+a.placement)),K=g(function(){var a=angular.isDefined(E.offsetHeight)?E.offsetHeight:E.prop("offsetHeight"),b=i.adjustTop(e,d,c,a);b&&E.css(b),K=null},0,!1),E.hasClass("uib-position-measure")?(i.positionArrow(E,a.placement),E.removeClass("uib-position-measure")):L!==a.placement&&i.positionArrow(E,a.placement),L=a.placement,J=null},0,!1)))};P.origScope=a,P.isOpen=!1,P.contentExp=function(){return P.content},d.$observe("disabled",function(a){a&&s(),a&&P.isOpen&&t()}),R&&a.$watch(R,function(a){P&&!a===P.isOpen&&j()});var V=function(){N.show.forEach(function(a){"outsideClick"===a?b.off("click",j):(b.off(a,m),b.off(a,j)),b.off("keypress",C)}),N.hide.forEach(function(a){"outsideClick"===a?h.off("click",B):b.off(a,q)})};D();var W=a.$eval(d[k+"Animation"]);P.animation=angular.isDefined(W)?!!W:n.animation;var X,Y=k+"AppendToBody";X=Y in d&&void 0===d[Y]?!0:a.$eval(d[Y]),M=angular.isDefined(X)?X:M,a.$on("$destroy",function(){V(),w(),P=null})}}}}}]}).directive("uibTooltipTemplateTransclude",["$animate","$sce","$compile","$templateRequest",function(a,b,c,d){return{link:function(e,f,g){var h,i,j,k=e.$eval(g.tooltipTemplateTranscludeScope),l=0,m=function(){i&&(i.remove(),i=null),h&&(h.$destroy(),h=null),j&&(a.leave(j).then(function(){i=null}),i=j,j=null)};e.$watch(b.parseAsResourceUrl(g.uibTooltipTemplateTransclude),function(b){var g=++l;b?(d(b,!0).then(function(d){if(g===l){var e=k.$new(),i=d,n=c(i)(e,function(b){m(),a.enter(b,f)});h=e,j=n,h.$emit("$includeContentLoaded",b)}},function(){g===l&&(m(),e.$emit("$includeContentError",b))}),e.$emit("$includeContentRequested",b)):m()}),e.$on("$destroy",m)}}}]).directive("uibTooltipClasses",["$uibPosition",function(a){return{restrict:"A",link:function(b,c,d){if(b.placement){var e=a.parsePlacement(b.placement);c.addClass(e[0])}b.popupClass&&c.addClass(b.popupClass),b.animation&&c.addClass(d.tooltipAnimationClass)}}}]).directive("uibTooltipPopup",function(){return{restrict:"A",scope:{content:"@"},templateUrl:"uib/template/tooltip/tooltip-popup.html"}}).directive("uibTooltip",["$uibTooltip",function(a){return a("uibTooltip","tooltip","mouseenter")}]).directive("uibTooltipTemplatePopup",function(){return{restrict:"A",scope:{contentExp:"&",originScope:"&"},templateUrl:"uib/template/tooltip/tooltip-template-popup.html"}}).directive("uibTooltipTemplate",["$uibTooltip",function(a){return a("uibTooltipTemplate","tooltip","mouseenter",{useContentExp:!0})}]).directive("uibTooltipHtmlPopup",function(){return{restrict:"A",scope:{contentExp:"&"},templateUrl:"uib/template/tooltip/tooltip-html-popup.html"}}).directive("uibTooltipHtml",["$uibTooltip",function(a){return a("uibTooltipHtml","tooltip","mouseenter",{useContentExp:!0})}]),angular.module("ui.bootstrap.popover",["ui.bootstrap.tooltip"]).directive("uibPopoverTemplatePopup",function(){return{restrict:"A",scope:{uibTitle:"@",contentExp:"&",originScope:"&"},templateUrl:"uib/template/popover/popover-template.html"}}).directive("uibPopoverTemplate",["$uibTooltip",function(a){return a("uibPopoverTemplate","popover","click",{useContentExp:!0})}]).directive("uibPopoverHtmlPopup",function(){return{restrict:"A",scope:{contentExp:"&",uibTitle:"@"},templateUrl:"uib/template/popover/popover-html.html"}}).directive("uibPopoverHtml",["$uibTooltip",function(a){return a("uibPopoverHtml","popover","click",{useContentExp:!0})}]).directive("uibPopoverPopup",function(){return{restrict:"A",scope:{uibTitle:"@",content:"@"},templateUrl:"uib/template/popover/popover.html"}}).directive("uibPopover",["$uibTooltip",function(a){return a("uibPopover","popover","click")}]),angular.module("ui.bootstrap.progressbar",[]).constant("uibProgressConfig",{animate:!0,max:100}).controller("UibProgressController",["$scope","$attrs","uibProgressConfig",function(a,b,c){function d(){return angular.isDefined(a.maxParam)?a.maxParam:c.max}var e=this,f=angular.isDefined(b.animate)?a.$parent.$eval(b.animate):c.animate;this.bars=[],a.max=d(),this.addBar=function(a,b,c){f||b.css({transition:"none"}),this.bars.push(a),a.max=d(),a.title=c&&angular.isDefined(c.title)?c.title:"progressbar",a.$watch("value",function(b){a.recalculatePercentage()}),a.recalculatePercentage=function(){var b=e.bars.reduce(function(a,b){return b.percent=+(100*b.value/b.max).toFixed(2),a+b.percent},0);b>100&&(a.percent-=b-100)},a.$on("$destroy",function(){b=null,e.removeBar(a)})},this.removeBar=function(a){this.bars.splice(this.bars.indexOf(a),1),this.bars.forEach(function(a){a.recalculatePercentage()})},a.$watch("maxParam",function(a){e.bars.forEach(function(a){a.max=d(),a.recalculatePercentage()})})}]).directive("uibProgress",function(){return{replace:!0,transclude:!0,controller:"UibProgressController",require:"uibProgress",scope:{maxParam:"=?max"},templateUrl:"uib/template/progressbar/progress.html"}}).directive("uibBar",function(){return{replace:!0,transclude:!0,require:"^uibProgress",scope:{value:"=",type:"@"},templateUrl:"uib/template/progressbar/bar.html",link:function(a,b,c,d){d.addBar(a,b,c)}}}).directive("uibProgressbar",function(){return{replace:!0,transclude:!0,controller:"UibProgressController",scope:{value:"=",maxParam:"=?max",type:"@"},templateUrl:"uib/template/progressbar/progressbar.html",link:function(a,b,c,d){d.addBar(a,angular.element(b.children()[0]),{title:c.title})}}}),angular.module("ui.bootstrap.rating",[]).constant("uibRatingConfig",{max:5,stateOn:null,stateOff:null,enableReset:!0,titles:["one","two","three","four","five"]}).controller("UibRatingController",["$scope","$attrs","uibRatingConfig",function(a,b,c){var d={$setViewValue:angular.noop},e=this;this.init=function(e){d=e,d.$render=this.render,d.$formatters.push(function(a){return angular.isNumber(a)&&a<<0!==a&&(a=Math.round(a)),a}),this.stateOn=angular.isDefined(b.stateOn)?a.$parent.$eval(b.stateOn):c.stateOn,this.stateOff=angular.isDefined(b.stateOff)?a.$parent.$eval(b.stateOff):c.stateOff,this.enableReset=angular.isDefined(b.enableReset)?a.$parent.$eval(b.enableReset):c.enableReset;var f=angular.isDefined(b.titles)?a.$parent.$eval(b.titles):c.titles;this.titles=angular.isArray(f)&&f.length>0?f:c.titles;var g=angular.isDefined(b.ratingStates)?a.$parent.$eval(b.ratingStates):new Array(angular.isDefined(b.max)?a.$parent.$eval(b.max):c.max);a.range=this.buildTemplateObjects(g)},this.buildTemplateObjects=function(a){for(var b=0,c=a.length;c>b;b++)a[b]=angular.extend({index:b},{stateOn:this.stateOn,stateOff:this.stateOff,title:this.getTitle(b)},a[b]);return a},this.getTitle=function(a){return a>=this.titles.length?a+1:this.titles[a]},a.rate=function(b){if(!a.readonly&&b>=0&&b<=a.range.length){var c=e.enableReset&&d.$viewValue===b?0:b;d.$setViewValue(c),d.$render()}},a.enter=function(b){a.readonly||(a.value=b),a.onHover({value:b})},a.reset=function(){a.value=d.$viewValue,a.onLeave()},a.onKeydown=function(b){/(37|38|39|40)/.test(b.which)&&(b.preventDefault(),b.stopPropagation(),a.rate(a.value+(38===b.which||39===b.which?1:-1)))},this.render=function(){a.value=d.$viewValue,a.title=e.getTitle(a.value-1)}}]).directive("uibRating",function(){return{require:["uibRating","ngModel"],restrict:"A",scope:{readonly:"=?readOnly",onHover:"&",onLeave:"&"},controller:"UibRatingController",templateUrl:"uib/template/rating/rating.html",link:function(a,b,c,d){var e=d[0],f=d[1];e.init(f)}}}),angular.module("ui.bootstrap.tabs",[]).controller("UibTabsetController",["$scope",function(a){function b(a){for(var b=0;bb.index?1:a.index0&&13>b:b>=0&&24>b;return c&&""!==a.hours?(a.showMeridian&&(12===b&&(b=0),a.meridian===y[1]&&(b+=12)),b):void 0}function i(){var b=+a.minutes,c=b>=0&&60>b;return c&&""!==a.minutes?b:void 0}function j(){var b=+a.seconds;return b>=0&&60>b?b:void 0}function k(a,b){return null===a?"":angular.isDefined(a)&&a.toString().length<2&&!b?"0"+a:a.toString()}function l(a){m(),x.$setViewValue(new Date(v)),n(a)}function m(){s&&s.$setValidity("hours",!0),t&&t.$setValidity("minutes",!0),u&&u.$setValidity("seconds",!0),x.$setValidity("time",!0),a.invalidHours=!1,a.invalidMinutes=!1,a.invalidSeconds=!1}function n(b){if(x.$modelValue){var c=v.getHours(),d=v.getMinutes(),e=v.getSeconds();a.showMeridian&&(c=0===c||12===c?12:c%12),a.hours="h"===b?c:k(c,!z),"m"!==b&&(a.minutes=k(d)),a.meridian=v.getHours()<12?y[0]:y[1],"s"!==b&&(a.seconds=k(e)),a.meridian=v.getHours()<12?y[0]:y[1]}else a.hours=null,a.minutes=null,a.seconds=null,a.meridian=y[0]}function o(a){v=q(v,a),l()}function p(a,b){return q(a,60*b)}function q(a,b){var c=new Date(a.getTime()+1e3*b),d=new Date(a);return d.setHours(c.getHours(),c.getMinutes(),c.getSeconds()),d}function r(){return(null===a.hours||""===a.hours)&&(null===a.minutes||""===a.minutes)&&(!a.showSeconds||a.showSeconds&&(null===a.seconds||""===a.seconds))}var s,t,u,v=new Date,w=[],x={$setViewValue:angular.noop},y=angular.isDefined(c.meridians)?a.$parent.$eval(c.meridians):g.meridians||f.DATETIME_FORMATS.AMPMS,z=angular.isDefined(c.padHours)?a.$parent.$eval(c.padHours):!0;a.tabindex=angular.isDefined(c.tabindex)?c.tabindex:0,b.removeAttr("tabindex"),this.init=function(b,d){x=b,x.$render=this.render,x.$formatters.unshift(function(a){return a?new Date(a):null});var e=d.eq(0),f=d.eq(1),h=d.eq(2);s=e.controller("ngModel"),t=f.controller("ngModel"),u=h.controller("ngModel");var i=angular.isDefined(c.mousewheel)?a.$parent.$eval(c.mousewheel):g.mousewheel;i&&this.setupMousewheelEvents(e,f,h);var j=angular.isDefined(c.arrowkeys)?a.$parent.$eval(c.arrowkeys):g.arrowkeys;j&&this.setupArrowkeyEvents(e,f,h),a.readonlyInput=angular.isDefined(c.readonlyInput)?a.$parent.$eval(c.readonlyInput):g.readonlyInput,this.setupInputEvents(e,f,h)};var A=g.hourStep;c.hourStep&&w.push(a.$parent.$watch(d(c.hourStep),function(a){A=+a}));var B=g.minuteStep;c.minuteStep&&w.push(a.$parent.$watch(d(c.minuteStep),function(a){B=+a}));var C;w.push(a.$parent.$watch(d(c.min),function(a){var b=new Date(a);C=isNaN(b)?void 0:b}));var D;w.push(a.$parent.$watch(d(c.max),function(a){var b=new Date(a);D=isNaN(b)?void 0:b}));var E=!1;c.ngDisabled&&w.push(a.$parent.$watch(d(c.ngDisabled),function(a){E=a})),a.noIncrementHours=function(){var a=p(v,60*A);return E||a>D||v>a&&C>a},a.noDecrementHours=function(){var a=p(v,60*-A);return E||C>a||a>v&&a>D},a.noIncrementMinutes=function(){var a=p(v,B);return E||a>D||v>a&&C>a},a.noDecrementMinutes=function(){var a=p(v,-B);return E||C>a||a>v&&a>D},a.noIncrementSeconds=function(){var a=q(v,F);return E||a>D||v>a&&C>a},a.noDecrementSeconds=function(){var a=q(v,-F);return E||C>a||a>v&&a>D},a.noToggleMeridian=function(){return v.getHours()<12?E||p(v,720)>D:E||p(v,-720)0};b.on("mousewheel wheel",function(b){E||a.$apply(e(b)?a.incrementHours():a.decrementHours()),b.preventDefault()}),c.on("mousewheel wheel",function(b){E||a.$apply(e(b)?a.incrementMinutes():a.decrementMinutes()),b.preventDefault()}),d.on("mousewheel wheel",function(b){E||a.$apply(e(b)?a.incrementSeconds():a.decrementSeconds()),b.preventDefault()})},this.setupArrowkeyEvents=function(b,c,d){b.on("keydown",function(b){E||(38===b.which?(b.preventDefault(),a.incrementHours(),a.$apply()):40===b.which&&(b.preventDefault(),a.decrementHours(),a.$apply()))}),c.on("keydown",function(b){E||(38===b.which?(b.preventDefault(),a.incrementMinutes(),a.$apply()):40===b.which&&(b.preventDefault(),a.decrementMinutes(),a.$apply()))}),d.on("keydown",function(b){E||(38===b.which?(b.preventDefault(),a.incrementSeconds(),a.$apply()):40===b.which&&(b.preventDefault(),a.decrementSeconds(),a.$apply()))})},this.setupInputEvents=function(b,c,d){if(a.readonlyInput)return a.updateHours=angular.noop,a.updateMinutes=angular.noop,void(a.updateSeconds=angular.noop);var e=function(b,c,d){x.$setViewValue(null),x.$setValidity("time",!1),angular.isDefined(b)&&(a.invalidHours=b,s&&s.$setValidity("hours",!1)),angular.isDefined(c)&&(a.invalidMinutes=c,t&&t.$setValidity("minutes",!1)),angular.isDefined(d)&&(a.invalidSeconds=d,u&&u.$setValidity("seconds",!1))};a.updateHours=function(){var a=h(),b=i();x.$setDirty(),angular.isDefined(a)&&angular.isDefined(b)?(v.setHours(a),v.setMinutes(b),C>v||v>D?e(!0):l("h")):e(!0)},b.on("blur",function(b){x.$setTouched(),r()?m():null===a.hours||""===a.hours?e(!0):!a.invalidHours&&a.hours<10&&a.$apply(function(){a.hours=k(a.hours,!z)})}),a.updateMinutes=function(){var a=i(),b=h();x.$setDirty(),angular.isDefined(a)&&angular.isDefined(b)?(v.setHours(b),v.setMinutes(a),C>v||v>D?e(void 0,!0):l("m")):e(void 0,!0)},c.on("blur",function(b){x.$setTouched(),r()?m():null===a.minutes?e(void 0,!0):!a.invalidMinutes&&a.minutes<10&&a.$apply(function(){a.minutes=k(a.minutes)})}),a.updateSeconds=function(){var a=j();x.$setDirty(),angular.isDefined(a)?(v.setSeconds(a),l("s")):e(void 0,void 0,!0)},d.on("blur",function(b){r()?m():!a.invalidSeconds&&a.seconds<10&&a.$apply(function(){a.seconds=k(a.seconds)})})},this.render=function(){var b=x.$viewValue;isNaN(b)?(x.$setValidity("time",!1),e.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.')):(b&&(v=b),C>v||v>D?(x.$setValidity("time",!1),a.invalidHours=!0,a.invalidMinutes=!0):m(),n())},a.showSpinners=angular.isDefined(c.showSpinners)?a.$parent.$eval(c.showSpinners):g.showSpinners,a.incrementHours=function(){a.noIncrementHours()||o(60*A*60)},a.decrementHours=function(){a.noDecrementHours()||o(60*-A*60)},a.incrementMinutes=function(){a.noIncrementMinutes()||o(60*B)},a.decrementMinutes=function(){a.noDecrementMinutes()||o(60*-B)},a.incrementSeconds=function(){a.noIncrementSeconds()||o(F)},a.decrementSeconds=function(){a.noDecrementSeconds()||o(-F)},a.toggleMeridian=function(){var b=i(),c=h();a.noToggleMeridian()||(angular.isDefined(b)&&angular.isDefined(c)?o(720*(v.getHours()<12?60:-60)):a.meridian=a.meridian===y[0]?y[1]:y[0])},a.blur=function(){x.$setTouched()},a.$on("$destroy",function(){for(;w.length;)w.shift()()})}]).directive("uibTimepicker",["uibTimepickerConfig",function(a){return{require:["uibTimepicker","?^ngModel"],restrict:"A",controller:"UibTimepickerController",controllerAs:"timepicker",scope:{},templateUrl:function(b,c){return c.templateUrl||a.templateUrl},link:function(a,b,c,d){var e=d[0],f=d[1];f&&e.init(f,b.find("input"))}}}]),angular.module("ui.bootstrap.typeahead",["ui.bootstrap.debounce","ui.bootstrap.position"]).factory("uibTypeaheadParser",["$parse",function(a){var b=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;return{parse:function(c){var d=c.match(b);if(!d)throw new Error('Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_" but got "'+c+'".');return{itemName:d[3],source:a(d[4]),viewMapper:a(d[2]||d[1]),modelMapper:a(d[1])}}}}]).controller("UibTypeaheadController",["$scope","$element","$attrs","$compile","$parse","$q","$timeout","$document","$window","$rootScope","$$debounce","$uibPosition","uibTypeaheadParser",function(a,b,c,d,e,f,g,h,i,j,k,l,m){function n(){P.moveInProgress||(P.moveInProgress=!0,P.$digest()),$()}function o(){P.position=F?l.offset(b):l.position(b),P.position.top+=b.prop("offsetHeight")}function p(a){var b;return angular.version.minor<6?(b=a.$options||{},b.getOption=function(a){return b[a]}):b=a.$options,b}var q,r,s=[9,13,27,38,40],t=200,u=a.$eval(c.typeaheadMinLength);u||0===u||(u=1),a.$watch(c.typeaheadMinLength,function(a){u=a||0===a?a:1});var v=a.$eval(c.typeaheadWaitMs)||0,w=a.$eval(c.typeaheadEditable)!==!1;a.$watch(c.typeaheadEditable,function(a){w=a!==!1});var x,y,z=e(c.typeaheadLoading).assign||angular.noop,A=c.typeaheadShouldSelect?e(c.typeaheadShouldSelect):function(a,b){var c=b.$event;return 13===c.which||9===c.which},B=e(c.typeaheadOnSelect),C=angular.isDefined(c.typeaheadSelectOnBlur)?a.$eval(c.typeaheadSelectOnBlur):!1,D=e(c.typeaheadNoResults).assign||angular.noop,E=c.typeaheadInputFormatter?e(c.typeaheadInputFormatter):void 0,F=c.typeaheadAppendToBody?a.$eval(c.typeaheadAppendToBody):!1,G=c.typeaheadAppendTo?a.$eval(c.typeaheadAppendTo):null,H=a.$eval(c.typeaheadFocusFirst)!==!1,I=c.typeaheadSelectOnExact?a.$eval(c.typeaheadSelectOnExact):!1,J=e(c.typeaheadIsOpen).assign||angular.noop,K=a.$eval(c.typeaheadShowHint)||!1,L=e(c.ngModel),M=e(c.ngModel+"($$$p)"),N=function(b,c){return angular.isFunction(L(a))&&r.getOption("getterSetter")?M(b,{$$$p:c}):L.assign(b,c)},O=m.parse(c.uibTypeahead),P=a.$new(),Q=a.$on("$destroy",function(){P.$destroy()});P.$on("$destroy",Q);var R="typeahead-"+P.$id+"-"+Math.floor(1e4*Math.random());b.attr({"aria-autocomplete":"list","aria-expanded":!1,"aria-owns":R});var S,T;K&&(S=angular.element("
"),S.css("position","relative"),b.after(S),T=b.clone(),T.attr("placeholder",""),T.attr("tabindex","-1"),T.val(""),T.css({position:"absolute",top:"0px",left:"0px","border-color":"transparent","box-shadow":"none",opacity:1,background:"none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 255, 255)",color:"#999"}),b.css({position:"relative","vertical-align":"top","background-color":"transparent"}),T.attr("id")&&T.removeAttr("id"),S.append(T),T.after(b));var U=angular.element("
");U.attr({id:R,matches:"matches",active:"activeIdx",select:"select(activeIdx, evt)","move-in-progress":"moveInProgress",query:"query",position:"position","assign-is-open":"assignIsOpen(isOpen)",debounce:"debounceUpdate"}),angular.isDefined(c.typeaheadTemplateUrl)&&U.attr("template-url",c.typeaheadTemplateUrl),angular.isDefined(c.typeaheadPopupTemplateUrl)&&U.attr("popup-template-url",c.typeaheadPopupTemplateUrl);var V=function(){K&&T.val("")},W=function(){P.matches=[],P.activeIdx=-1,b.attr("aria-expanded",!1),V()},X=function(a){return R+"-option-"+a};P.$watch("activeIdx",function(a){0>a?b.removeAttr("aria-activedescendant"):b.attr("aria-activedescendant",X(a))});var Y=function(a,b){return P.matches.length>b&&a?a.toUpperCase()===P.matches[b].label.toUpperCase():!1},Z=function(c,d){var e={$viewValue:c};z(a,!0),D(a,!1),f.when(O.source(a,e)).then(function(f){var g=c===q.$viewValue;if(g&&x)if(f&&f.length>0){P.activeIdx=H?0:-1,D(a,!1),P.matches.length=0;for(var h=0;h0&&i.slice(0,c.length).toUpperCase()===c.toUpperCase()?T.val(c+i.slice(c.length)):T.val("")}}else W(),D(a,!0);g&&z(a,!1)},function(){W(),z(a,!1),D(a,!0)})};F&&(angular.element(i).on("resize",n),h.find("body").on("scroll",n));var $=k(function(){P.matches.length&&o(),P.moveInProgress=!1},t);P.moveInProgress=!1,P.query=void 0;var _,aa=function(a){_=g(function(){Z(a)},v)},ba=function(){_&&g.cancel(_)};W(),P.assignIsOpen=function(b){J(a,b)},P.select=function(d,e){var f,h,i={};y=!0,i[O.itemName]=h=P.matches[d].model,f=O.modelMapper(a,i),N(a,f),q.$setValidity("editable",!0),q.$setValidity("parse",!0),B(a,{$item:h,$model:f,$label:O.viewMapper(a,i),$event:e}),W(),P.$eval(c.typeaheadFocusOnSelect)!==!1&&g(function(){b[0].focus()},0,!1)},b.on("keydown",function(b){if(0!==P.matches.length&&-1!==s.indexOf(b.which)){var c=A(a,{$event:b});if(-1===P.activeIdx&&c||9===b.which&&b.shiftKey)return W(),void P.$digest();b.preventDefault();var d;switch(b.which){case 27:b.stopPropagation(),W(),a.$digest();break;case 38:P.activeIdx=(P.activeIdx>0?P.activeIdx:P.matches.length)-1,P.$digest(),d=U[0].querySelectorAll(".uib-typeahead-match")[P.activeIdx],d.parentNode.scrollTop=d.offsetTop;break;case 40:P.activeIdx=(P.activeIdx+1)%P.matches.length,P.$digest(),d=U[0].querySelectorAll(".uib-typeahead-match")[P.activeIdx], +d.parentNode.scrollTop=d.offsetTop;break;default:c&&P.$apply(function(){angular.isNumber(P.debounceUpdate)||angular.isObject(P.debounceUpdate)?k(function(){P.select(P.activeIdx,b)},angular.isNumber(P.debounceUpdate)?P.debounceUpdate:P.debounceUpdate["default"]):P.select(P.activeIdx,b)})}}}),b.on("focus",function(a){x=!0,0!==u||q.$viewValue||g(function(){Z(q.$viewValue,a)},0)}),b.on("blur",function(a){C&&P.matches.length&&-1!==P.activeIdx&&!y&&(y=!0,P.$apply(function(){angular.isObject(P.debounceUpdate)&&angular.isNumber(P.debounceUpdate.blur)?k(function(){P.select(P.activeIdx,a)},P.debounceUpdate.blur):P.select(P.activeIdx,a)})),!w&&q.$error.editable&&(q.$setViewValue(),P.$apply(function(){q.$setValidity("editable",!0),q.$setValidity("parse",!0)}),b.val("")),x=!1,y=!1});var ca=function(c){b[0]!==c.target&&3!==c.which&&0!==P.matches.length&&(W(),j.$$phase||a.$digest())};h.on("click",ca),a.$on("$destroy",function(){h.off("click",ca),(F||G)&&da.remove(),F&&(angular.element(i).off("resize",n),h.find("body").off("scroll",n)),U.remove(),K&&S.remove()});var da=d(U)(P);F?h.find("body").append(da):G?angular.element(G).eq(0).append(da):b.after(da),this.init=function(b){q=b,r=p(q),P.debounceUpdate=e(r.getOption("debounce"))(a),q.$parsers.unshift(function(b){return x=!0,0===u||b&&b.length>=u?v>0?(ba(),aa(b)):Z(b):(z(a,!1),ba(),W()),w?b:b?void q.$setValidity("editable",!1):(q.$setValidity("editable",!0),null)}),q.$formatters.push(function(b){var c,d,e={};return w||q.$setValidity("editable",!0),E?(e.$model=b,E(a,e)):(e[O.itemName]=b,c=O.viewMapper(a,e),e[O.itemName]=void 0,d=O.viewMapper(a,e),c!==d?c:b)})}}]).directive("uibTypeahead",function(){return{controller:"UibTypeaheadController",require:["ngModel","uibTypeahead"],link:function(a,b,c,d){d[1].init(d[0])}}}).directive("uibTypeaheadPopup",["$$debounce",function(a){return{scope:{matches:"=",query:"=",active:"=",position:"&",moveInProgress:"=",select:"&",assignIsOpen:"&",debounce:"&"},replace:!0,templateUrl:function(a,b){return b.popupTemplateUrl||"uib/template/typeahead/typeahead-popup.html"},link:function(b,c,d){b.templateUrl=d.templateUrl,b.isOpen=function(){var a=b.matches.length>0;return b.assignIsOpen({isOpen:a}),a},b.isActive=function(a){return b.active===a},b.selectActive=function(a){b.active=a},b.selectMatch=function(c,d){var e=b.debounce();angular.isNumber(e)||angular.isObject(e)?a(function(){b.select({activeIdx:c,evt:d})},angular.isNumber(e)?e:e["default"]):b.select({activeIdx:c,evt:d})}}}}]).directive("uibTypeaheadMatch",["$templateRequest","$compile","$parse",function(a,b,c){return{scope:{index:"=",match:"=",query:"="},link:function(d,e,f){var g=c(f.templateUrl)(d.$parent)||"uib/template/typeahead/typeahead-match.html";a(g).then(function(a){var c=angular.element(a.trim());e.replaceWith(c),b(c)(d)})}}}]).filter("uibTypeaheadHighlight",["$sce","$injector","$log",function(a,b,c){function d(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}function e(a){return/<.*>/g.test(a)}var f;return f=b.has("$sanitize"),function(b,g){return!f&&e(b)&&c.warn("Unsafe use of typeahead please use ngSanitize"),b=g?(""+b).replace(new RegExp(d(g),"gi"),"$&"):b,f||(b=a.trustAsHtml(b)),b}}]),angular.module("uib/template/accordion/accordion-group.html",[]).run(["$templateCache",function(a){a.put("uib/template/accordion/accordion-group.html",'\n
\n
\n
\n')}]),angular.module("uib/template/accordion/accordion.html",[]).run(["$templateCache",function(a){a.put("uib/template/accordion/accordion.html",'
')}]),angular.module("uib/template/alert/alert.html",[]).run(["$templateCache",function(a){a.put("uib/template/alert/alert.html",'\n
\n')}]),angular.module("uib/template/carousel/carousel.html",[]).run(["$templateCache",function(a){a.put("uib/template/carousel/carousel.html",'\n\n \n previous\n\n\n \n next\n\n\n')}]),angular.module("uib/template/carousel/slide.html",[]).run(["$templateCache",function(a){a.put("uib/template/carousel/slide.html",'
\n')}]),angular.module("uib/template/datepicker/datepicker.html",[]).run(["$templateCache",function(a){a.put("uib/template/datepicker/datepicker.html",'
\n
\n
\n
\n
\n')}]),angular.module("uib/template/datepicker/day.html",[]).run(["$templateCache",function(a){a.put("uib/template/datepicker/day.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
{{::label.abbr}}
{{ weekNumbers[$index] }}\n \n
\n')}]),angular.module("uib/template/datepicker/month.html",[]).run(["$templateCache",function(a){a.put("uib/template/datepicker/month.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n
\n')}]),angular.module("uib/template/datepicker/year.html",[]).run(["$templateCache",function(a){a.put("uib/template/datepicker/year.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n
\n \n
\n')}]),angular.module("uib/template/datepickerPopup/popup.html",[]).run(["$templateCache",function(a){a.put("uib/template/datepickerPopup/popup.html",'\n')}]),angular.module("uib/template/modal/window.html",[]).run(["$templateCache",function(a){a.put("uib/template/modal/window.html","
\n")}]),angular.module("uib/template/pager/pager.html",[]).run(["$templateCache",function(a){a.put("uib/template/pager/pager.html",'
  • {{::getText(\'previous\')}}
  • \n
  • {{::getText(\'next\')}}
  • \n')}]),angular.module("uib/template/pagination/pagination.html",[]).run(["$templateCache",function(a){a.put("uib/template/pagination/pagination.html",'\n\n\n\n\n')}]),angular.module("uib/template/tooltip/tooltip-html-popup.html",[]).run(["$templateCache",function(a){a.put("uib/template/tooltip/tooltip-html-popup.html",'
    \n
    \n')}]),angular.module("uib/template/tooltip/tooltip-popup.html",[]).run(["$templateCache",function(a){a.put("uib/template/tooltip/tooltip-popup.html",'
    \n
    \n')}]),angular.module("uib/template/tooltip/tooltip-template-popup.html",[]).run(["$templateCache",function(a){a.put("uib/template/tooltip/tooltip-template-popup.html",'
    \n
    \n')}]),angular.module("uib/template/popover/popover-html.html",[]).run(["$templateCache",function(a){a.put("uib/template/popover/popover-html.html",'
    \n\n
    \n

    \n
    \n
    \n')}]),angular.module("uib/template/popover/popover-template.html",[]).run(["$templateCache",function(a){a.put("uib/template/popover/popover-template.html",'
    \n\n
    \n

    \n
    \n
    \n')}]),angular.module("uib/template/popover/popover.html",[]).run(["$templateCache",function(a){a.put("uib/template/popover/popover.html",'
    \n\n
    \n

    \n
    \n
    \n')}]),angular.module("uib/template/progressbar/bar.html",[]).run(["$templateCache",function(a){a.put("uib/template/progressbar/bar.html",'
    \n')}]),angular.module("uib/template/progressbar/progress.html",[]).run(["$templateCache",function(a){a.put("uib/template/progressbar/progress.html",'
    ')}]),angular.module("uib/template/progressbar/progressbar.html",[]).run(["$templateCache",function(a){a.put("uib/template/progressbar/progressbar.html",'
    \n
    \n
    \n')}]),angular.module("uib/template/rating/rating.html",[]).run(["$templateCache",function(a){a.put("uib/template/rating/rating.html",'\n ({{ $index < value ? \'*\' : \' \' }})\n \n\n')}]),angular.module("uib/template/tabs/tab.html",[]).run(["$templateCache",function(a){a.put("uib/template/tabs/tab.html",'\n')}]),angular.module("uib/template/tabs/tabset.html",[]).run(["$templateCache",function(a){a.put("uib/template/tabs/tabset.html",'
    \n \n
    \n
    \n
    \n
    \n
    \n')}]),angular.module("uib/template/timepicker/timepicker.html",[]).run(["$templateCache",function(a){a.put("uib/template/timepicker/timepicker.html",'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      
    \n \n :\n \n :\n \n
      
    \n')}]),angular.module("uib/template/typeahead/typeahead-match.html",[]).run(["$templateCache",function(a){a.put("uib/template/typeahead/typeahead-match.html",'\n')}]),angular.module("uib/template/typeahead/typeahead-popup.html",[]).run(["$templateCache",function(a){a.put("uib/template/typeahead/typeahead-popup.html",'\n')}]),angular.module("ui.bootstrap.carousel").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibCarouselCss&&angular.element(document).find("head").prepend(''),angular.$$uibCarouselCss=!0}),angular.module("ui.bootstrap.datepicker").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibDatepickerCss&&angular.element(document).find("head").prepend(''),angular.$$uibDatepickerCss=!0}),angular.module("ui.bootstrap.position").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibPositionCss&&angular.element(document).find("head").prepend(''),angular.$$uibPositionCss=!0}),angular.module("ui.bootstrap.datepickerPopup").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibDatepickerpopupCss&&angular.element(document).find("head").prepend(''),angular.$$uibDatepickerpopupCss=!0}),angular.module("ui.bootstrap.tooltip").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibTooltipCss&&angular.element(document).find("head").prepend(''),angular.$$uibTooltipCss=!0}),angular.module("ui.bootstrap.timepicker").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibTimepickerCss&&angular.element(document).find("head").prepend(''),angular.$$uibTimepickerCss=!0}),angular.module("ui.bootstrap.typeahead").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibTypeaheadCss&&angular.element(document).find("head").prepend(''),angular.$$uibTypeaheadCss=!0}); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.css b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.css new file mode 100644 index 0000000..102a1ae --- /dev/null +++ b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.css @@ -0,0 +1,68 @@ +.angular-ui-tree { +} + +.angular-ui-tree-empty, .angular-ui-tree-dropzone { + border: 1px dashed #bbb; + min-height: 100px; + background-color: #e5e5e5; + background-image: -webkit-linear-gradient(45deg, #fff 25%, transparent 25%, transparent 75%, #fff 75%, #fff), -webkit-linear-gradient(45deg, #fff 25%, transparent 25%, transparent 75%, #fff 75%, #fff); + background-image: -moz-linear-gradient(45deg, #fff 25%, transparent 25%, transparent 75%, #fff 75%, #fff), -moz-linear-gradient(45deg, #fff 25%, transparent 25%, transparent 75%, #fff 75%, #fff); + background-image: linear-gradient(45deg, #fff 25%, transparent 25%, transparent 75%, #fff 75%, #fff), linear-gradient(45deg, #fff 25%, transparent 25%, transparent 75%, #fff 75%, #fff); + background-size: 60px 60px; + background-position: 0 0, 30px 30px; +} + +.angular-ui-tree-empty { + pointer-events: none; +} + +.angular-ui-tree-nodes { + position: relative; + margin: 0; + padding: 0; + list-style: none; +} + +.angular-ui-tree-nodes .angular-ui-tree-nodes { + padding-left: 20px; +} + +.angular-ui-tree-node, .angular-ui-tree-placeholder { + position: relative; + margin: 0; + padding: 0; + min-height: 20px; + line-height: 20px; +} + +.angular-ui-tree-hidden { + display: none; +} + +.angular-ui-tree-placeholder { + margin: 10px; + padding: 0; + min-height: 30px; +} + +.angular-ui-tree-handle { + cursor: move; + text-decoration: none; + font-weight: bold; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + min-height: 20px; + line-height: 20px; +} + +.angular-ui-tree-drag { + position: absolute; + pointer-events: none; + z-index: 999; + opacity: .8; +} + +.angular-ui-tree-drag .tree-node-content { + margin-top: 0; +} diff --git a/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.js b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.js new file mode 100644 index 0000000..305980f --- /dev/null +++ b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.js @@ -0,0 +1,1867 @@ +/** + * @license Angular UI Tree v2.22.5 + * (c) 2010-2017. https://github.com/angular-ui-tree/angular-ui-tree + * License: MIT + */ +(function () { + 'use strict'; + + angular.module('ui.tree', []) + .constant('treeConfig', { + treeClass: 'angular-ui-tree', + emptyTreeClass: 'angular-ui-tree-empty', + dropzoneClass: 'angular-ui-tree-dropzone', + hiddenClass: 'angular-ui-tree-hidden', + nodesClass: 'angular-ui-tree-nodes', + nodeClass: 'angular-ui-tree-node', + handleClass: 'angular-ui-tree-handle', + placeholderClass: 'angular-ui-tree-placeholder', + dragClass: 'angular-ui-tree-drag', + dragThreshold: 3, + defaultCollapsed: false, + appendChildOnHover: true + }); + +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + + .controller('TreeHandleController', ['$scope', '$element', + function ($scope, $element) { + this.scope = $scope; + + $scope.$element = $element; + $scope.$nodeScope = null; + $scope.$type = 'uiTreeHandle'; + + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + .controller('TreeNodeController', ['$scope', '$element', + function ($scope, $element) { + this.scope = $scope; + + $scope.$element = $element; + $scope.$modelValue = null; // Model value for node; + $scope.$parentNodeScope = null; // uiTreeNode Scope of parent node; + $scope.$childNodesScope = null; // uiTreeNodes Scope of child nodes. + $scope.$parentNodesScope = null; // uiTreeNodes Scope of parent nodes. + $scope.$treeScope = null; // uiTree scope + $scope.$handleScope = null; // it's handle scope + $scope.$type = 'uiTreeNode'; + $scope.$$allowNodeDrop = false; + $scope.collapsed = false; + $scope.expandOnHover = false; + + //Called by uiTreeNode Directive on load. + $scope.init = function (controllersArr) { + var treeNodesCtrl = controllersArr[0]; + $scope.$treeScope = controllersArr[1] ? controllersArr[1].scope : null; + + //Find the scope of it's parent node. + $scope.$parentNodeScope = treeNodesCtrl.scope.$nodeScope; + + //modelValue for current node. + $scope.$modelValue = treeNodesCtrl.scope.$modelValue[$scope.$index]; + $scope.$parentNodesScope = treeNodesCtrl.scope; + + //Init sub nodes. + treeNodesCtrl.scope.initSubNode($scope); + + $element.on('$destroy', function () { + + //Destroy sub nodes. + treeNodesCtrl.scope.destroySubNode($scope); + }); + }; + + //Return the index of child node in parent node (nodesScope). + $scope.index = function () { + return $scope.$parentNodesScope.$modelValue.indexOf($scope.$modelValue); + }; + + $scope.dragEnabled = function () { + return !($scope.$treeScope && !$scope.$treeScope.dragEnabled); + }; + + $scope.isSibling = function (targetNode) { + return $scope.$parentNodesScope == targetNode.$parentNodesScope; + }; + + $scope.isChild = function (targetNode) { + var nodes = $scope.childNodes(); + return nodes && nodes.indexOf(targetNode) > -1; + }; + + //TODO(jcarter): This method is on uiTreeHelper already. + $scope.prev = function () { + var index = $scope.index(); + if (index > 0) { + return $scope.siblings()[index - 1]; + } + return null; + }; + + //Calls childNodes on parent. + $scope.siblings = function () { + return $scope.$parentNodesScope.childNodes(); + }; + + $scope.childNodesCount = function () { + return $scope.childNodes() ? $scope.childNodes().length : 0; + }; + + $scope.hasChild = function () { + return $scope.childNodesCount() > 0; + }; + + $scope.childNodes = function () { + return $scope.$childNodesScope && $scope.$childNodesScope.$modelValue ? + $scope.$childNodesScope.childNodes() : + null; + }; + + $scope.accept = function (sourceNode, destIndex) { + return $scope.$childNodesScope && + $scope.$childNodesScope.$modelValue && + $scope.$childNodesScope.accept(sourceNode, destIndex); + }; + + $scope.remove = function () { + return $scope.$parentNodesScope.removeNode($scope); + }; + + $scope.toggle = function () { + $scope.collapsed = !$scope.collapsed; + $scope.$treeScope.$callbacks.toggle($scope.collapsed, $scope); + }; + + $scope.collapse = function () { + $scope.collapsed = true; + }; + + $scope.expand = function () { + $scope.collapsed = false; + }; + + $scope.depth = function () { + var parentNode = $scope.$parentNodeScope; + if (parentNode) { + return parentNode.depth() + 1; + } + return 1; + }; + + /** + * Returns the depth of the deepest subtree under this node + * @param scope a TreeNodesController scope object + * @returns Depth of all nodes *beneath* this node. If scope belongs to a leaf node, the + * result is 0 (it has no subtree). + */ + function countSubTreeDepth(scope) { + if (!scope) { + return 0; + } + var thisLevelDepth = 0, + childNodes = scope.childNodes(), + childNode, + childDepth, + i; + if (!childNodes || childNodes.length === 0) { + return 0; + } + for (i = childNodes.length - 1; i >= 0 ; i--) { + childNode = childNodes[i], + childDepth = 1 + countSubTreeDepth(childNode); + thisLevelDepth = Math.max(thisLevelDepth, childDepth); + } + return thisLevelDepth; + } + + $scope.maxSubDepth = function () { + return $scope.$childNodesScope ? countSubTreeDepth($scope.$childNodesScope) : 0; + }; + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + + .controller('TreeNodesController', ['$scope', '$element', + function ($scope, $element) { + this.scope = $scope; + + $scope.$element = $element; + $scope.$modelValue = null; + $scope.$nodeScope = null; // the scope of node which the nodes belongs to + $scope.$treeScope = null; + $scope.$type = 'uiTreeNodes'; + $scope.$nodesMap = {}; + + $scope.nodropEnabled = false; + $scope.maxDepth = 0; + $scope.cloneEnabled = false; + + $scope.initSubNode = function (subNode) { + if (!subNode.$modelValue) { + return null; + } + $scope.$nodesMap[subNode.$modelValue.$$hashKey] = subNode; + }; + + $scope.destroySubNode = function (subNode) { + if (!subNode.$modelValue) { + return null; + } + $scope.$nodesMap[subNode.$modelValue.$$hashKey] = null; + }; + + $scope.accept = function (sourceNode, destIndex) { + return $scope.$treeScope.$callbacks.accept(sourceNode, $scope, destIndex); + }; + + $scope.beforeDrag = function (sourceNode) { + return $scope.$treeScope.$callbacks.beforeDrag(sourceNode); + }; + + $scope.isParent = function (node) { + return node.$parentNodesScope == $scope; + }; + + $scope.hasChild = function () { + return $scope.$modelValue.length > 0; + }; + + $scope.safeApply = function (fn) { + var phase = this.$root.$$phase; + if (phase == '$apply' || phase == '$digest') { + if (fn && (typeof (fn) === 'function')) { + fn(); + } + } else { + this.$apply(fn); + } + }; + + //Called in apply method of UiTreeHelper.dragInfo. + $scope.removeNode = function (node) { + var index = $scope.$modelValue.indexOf(node.$modelValue); + if (index > -1) { + $scope.safeApply(function () { + $scope.$modelValue.splice(index, 1)[0]; + }); + return $scope.$treeScope.$callbacks.removed(node); + } + return null; + }; + + //Called in apply method of UiTreeHelper.dragInfo. + $scope.insertNode = function (index, nodeData) { + $scope.safeApply(function () { + $scope.$modelValue.splice(index, 0, nodeData); + }); + }; + + $scope.childNodes = function () { + var i, nodes = []; + if ($scope.$modelValue) { + for (i = 0; i < $scope.$modelValue.length; i++) { + nodes.push($scope.$nodesMap[$scope.$modelValue[i].$$hashKey]); + } + } + return nodes; + }; + + $scope.depth = function () { + if ($scope.$nodeScope) { + return $scope.$nodeScope.depth(); + } + return 0; // if it has no $nodeScope, it's root + }; + + // check if depth limit has reached + $scope.outOfDepth = function (sourceNode) { + var maxDepth = $scope.maxDepth || $scope.$treeScope.maxDepth; + if (maxDepth > 0) { + return $scope.depth() + sourceNode.maxSubDepth() + 1 > maxDepth; + } + return false; + }; + + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + + .controller('TreeController', ['$scope', '$element', + function ($scope, $element) { + this.scope = $scope; + + $scope.$element = $element; + $scope.$nodesScope = null; // root nodes + $scope.$type = 'uiTree'; + $scope.$emptyElm = null; + $scope.$dropzoneElm = null; + $scope.$callbacks = null; + + $scope.dragEnabled = true; + $scope.emptyPlaceholderEnabled = true; + $scope.maxDepth = 0; + $scope.dragDelay = 0; + $scope.cloneEnabled = false; + $scope.nodropEnabled = false; + $scope.dropzoneEnabled = false; + + // Check if it's a empty tree + $scope.isEmpty = function () { + return ($scope.$nodesScope && $scope.$nodesScope.$modelValue + && $scope.$nodesScope.$modelValue.length === 0); + }; + + // add placeholder to empty tree + $scope.place = function (placeElm) { + $scope.$nodesScope.$element.append(placeElm); + $scope.$emptyElm.remove(); + }; + + this.resetEmptyElement = function () { + if ((!$scope.$nodesScope.$modelValue || $scope.$nodesScope.$modelValue.length === 0) && + $scope.emptyPlaceholderEnabled) { + $element.append($scope.$emptyElm); + } else { + $scope.$emptyElm.remove(); + } + }; + + this.resetDropzoneElement = function () { + if ((!$scope.$nodesScope.$modelValue || $scope.$nodesScope.$modelValue.length !== 0) && + $scope.dropzoneEnabled) { + $element.append($scope.$dropzoneElm); + } else { + $scope.$dropzoneElm.remove(); + } + }; + + $scope.resetEmptyElement = this.resetEmptyElement; + $scope.resetDropzoneElement = this.resetDropzoneElement; + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + .directive('uiTree', ['treeConfig', '$window', + function (treeConfig, $window) { + return { + restrict: 'A', + scope: true, + controller: 'TreeController', + link: function (scope, element, attrs, ctrl) { + var callbacks = { + accept: null, + beforeDrag: null + }, + config = {}, + tdElm, + $trElm, + emptyElmColspan; + + //Adding configured class to uiTree. + angular.extend(config, treeConfig); + + if (config.treeClass) { + element.addClass(config.treeClass); + } + + //Determining if uiTree is on a table. + if (element.prop('tagName').toLowerCase() === 'table') { + scope.$emptyElm = angular.element($window.document.createElement('tr')); + $trElm = element.find('tr'); + + //If we can find a tr, then we can use its td children as the empty element colspan. + if ($trElm.length > 0) { + emptyElmColspan = angular.element($trElm).children().length; + } else { + + //If not, by setting a huge colspan we make sure it takes full width. + //TODO(jcarter): Check for negative side effects. + emptyElmColspan = 1000000; + } + tdElm = angular.element($window.document.createElement('td')) + .attr('colspan', emptyElmColspan); + scope.$emptyElm.append(tdElm); + } else { + scope.$emptyElm = angular.element($window.document.createElement('div')); + scope.$dropzoneElm = angular.element($window.document.createElement('div')); + } + + if (config.emptyTreeClass) { + scope.$emptyElm.addClass(config.emptyTreeClass); + } + if (config.dropzoneClass) { + scope.$dropzoneElm.addClass(config.dropzoneClass); + } + + scope.$watch('$nodesScope.$modelValue.length', function (val) { + if (!angular.isNumber(val)) { + return; + } + + ctrl.resetEmptyElement(); + ctrl.resetDropzoneElement(); + }, true); + + scope.$watch(attrs.dragEnabled, function (val) { + if ((typeof val) == 'boolean') { + scope.dragEnabled = val; + } + }); + + scope.$watch(attrs.emptyPlaceholderEnabled, function (val) { + if ((typeof val) == 'boolean') { + scope.emptyPlaceholderEnabled = val; + ctrl.resetEmptyElement(); + } + }); + + scope.$watch(attrs.nodropEnabled, function (val) { + if ((typeof val) == 'boolean') { + scope.nodropEnabled = val; + } + }); + + scope.$watch(attrs.dropzoneEnabled, function (val) { + if ((typeof val) == 'boolean') { + scope.dropzoneEnabled = val; + ctrl.resetDropzoneElement(); + } + }); + + scope.$watch(attrs.cloneEnabled, function (val) { + if ((typeof val) == 'boolean') { + scope.cloneEnabled = val; + } + }); + + scope.$watch(attrs.maxDepth, function (val) { + if ((typeof val) == 'number') { + scope.maxDepth = val; + } + }); + + scope.$watch(attrs.dragDelay, function (val) { + if ((typeof val) == 'number') { + scope.dragDelay = val; + } + }); + + /** + * Callback checks if the destination node can accept the dragged node. + * By default, ui-tree will check that 'data-nodrop-enabled' is not set for the + * destination ui-tree-nodes, and that the 'max-depth' attribute will not be exceeded + * if it is set on the ui-tree or ui-tree-nodes. + * This callback can be overridden, but callers must manually enforce nodrop and max-depth + * themselves if they need those to be enforced. + * @param sourceNodeScope Scope of the ui-tree-node being dragged + * @param destNodesScope Scope of the ui-tree-nodes where the node is hovering + * @param destIndex Index in the destination nodes array where the source node will drop + * @returns {boolean} True if the node is permitted to be dropped here + */ + callbacks.accept = function (sourceNodeScope, destNodesScope, destIndex) { + return !(destNodesScope.nodropEnabled || destNodesScope.$treeScope.nodropEnabled || destNodesScope.outOfDepth(sourceNodeScope)); + }; + + callbacks.beforeDrag = function (sourceNodeScope) { + return true; + }; + + callbacks.expandTimeoutStart = function() + { + + }; + + callbacks.expandTimeoutCancel = function() + { + + }; + + callbacks.expandTimeoutEnd = function() + { + + }; + + callbacks.removed = function (node) { + + }; + + /** + * Callback is fired when a node is successfully dropped in a new location + * @param event + */ + callbacks.dropped = function (event) { + + }; + + /** + * Callback is fired each time the user starts dragging a node + * @param event + */ + callbacks.dragStart = function (event) { + + }; + + /** + * Callback is fired each time a dragged node is moved with the mouse/touch. + * @param event + */ + callbacks.dragMove = function (event) { + + }; + + /** + * Callback is fired when the tree exits drag mode. If the user dropped a node, the drop may have been + * accepted or reverted. + * @param event + */ + callbacks.dragStop = function (event) { + + }; + + /** + * Callback is fired when a user drops a node (but prior to processing the drop action) + * beforeDrop can return a Promise, truthy, or falsy (returning nothing is falsy). + * If it returns falsy, or a resolve Promise, the node move is accepted + * If it returns truthy, or a rejected Promise, the node move is reverted + * @param event + * @returns {Boolean|Promise} Truthy (or rejected Promise) to cancel node move; falsy (or resolved promise) + */ + callbacks.beforeDrop = function (event) { + + }; + + /** + * Callback is fired when a user toggles node (but after processing the toggle action) + * @param sourceNodeScope + * @param collapsed + */ + callbacks.toggle = function (collapsed, sourceNodeScope) { + + }; + + scope.$watch(attrs.uiTree, function (newVal, oldVal) { + angular.forEach(newVal, function (value, key) { + if (callbacks[key]) { + if (typeof value === 'function') { + callbacks[key] = value; + } + } + }); + + scope.$callbacks = callbacks; + }, true); + + + } + }; + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + .directive('uiTreeHandle', ['treeConfig', + function (treeConfig) { + return { + require: '^uiTreeNode', + restrict: 'A', + scope: true, + controller: 'TreeHandleController', + link: function (scope, element, attrs, treeNodeCtrl) { + var config = {}; + angular.extend(config, treeConfig); + if (config.handleClass) { + element.addClass(config.handleClass); + } + // connect with the tree node. + if (scope != treeNodeCtrl.scope) { + scope.$nodeScope = treeNodeCtrl.scope; + treeNodeCtrl.scope.$handleScope = scope; + } + } + }; + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + + .directive('uiTreeNode', ['treeConfig', 'UiTreeHelper', '$window', '$document', '$timeout', '$q', + function (treeConfig, UiTreeHelper, $window, $document, $timeout, $q) { + return { + require: ['^uiTreeNodes', '^uiTree'], + restrict: 'A', + controller: 'TreeNodeController', + link: function (scope, element, attrs, controllersArr) { + var config = {}, + hasTouch = 'ontouchstart' in window, + firstMoving, + dragInfo, + pos, + placeElm, + hiddenPlaceElm, + dragElm, + scrollContainerElm, + unhover, + treeScope = null, + elements, // As a parameter for callbacks + dragDelaying = true, + dragStarted = false, + dragTimer = null, + body = document.body, + html = document.documentElement, + document_height, + document_width, + dragStart, + tagName, + dragMove, + dragEnd, + dragStartEvent, + dragMoveEvent, + dragEndEvent, + dragCancelEvent, + dragDelay, + bindDragStartEvents, + bindDragMoveEvents, + unbindDragMoveEvents, + keydownHandler, + isHandleChild, + el, + isUiTreeRoot, + treeOfOrigin; + + //Adding configured class to ui-tree-node. + angular.extend(config, treeConfig); + + if (config.nodeClass) { + element.addClass(config.nodeClass); + } + + //Call init function in nodeCtrl, sets parent node and sets up sub nodes. + scope.init(controllersArr); + + scope.collapsed = !!UiTreeHelper.getNodeAttribute(scope, 'collapsed') || treeConfig.defaultCollapsed; + scope.expandOnHover = !!UiTreeHelper.getNodeAttribute(scope, 'expandOnHover'); + scope.scrollContainer = UiTreeHelper.getNodeAttribute(scope, 'scrollContainer') || attrs.scrollContainer || null; + scope.sourceOnly = scope.nodropEnabled || scope.$treeScope.nodropEnabled; + + scope.$watch(attrs.collapsed, function (val) { + if ((typeof val) == 'boolean') { + scope.collapsed = val; + } + }); + + //Watches to trigger behavior based on actions and settings. + scope.$watch('collapsed', function (val) { + UiTreeHelper.setNodeAttribute(scope, 'collapsed', val); + attrs.$set('collapsed', val); + }); + + scope.$watch(attrs.expandOnHover, function(val) { + if ((typeof val) === 'boolean' || (typeof val) === 'number') { + scope.expandOnHover = val; + } + }); + + scope.$watch('expandOnHover', function (val) { + UiTreeHelper.setNodeAttribute(scope, 'expandOnHover', val); + attrs.$set('expandOnHover', val); + }); + + attrs.$observe('scrollContainer', function(val) { + if ((typeof val) === 'string') { + scope.scrollContainer = val; + } + }); + + scope.$watch('scrollContainer', function(val) { + UiTreeHelper.setNodeAttribute(scope, 'scrollContainer', val); + attrs.$set('scrollContainer', val); + scrollContainerElm = document.querySelector(val); + }); + + scope.$on('angular-ui-tree:collapse-all', function () { + scope.collapsed = true; + }); + + scope.$on('angular-ui-tree:expand-all', function () { + scope.collapsed = false; + }); + + /** + * Called when the user has grabbed a node and started dragging it. + * + * @param {MouseEvent} e event that is triggered by DOM. + * @return undefined? + */ + dragStart = function (e) { + + //Disable right click. + if (!hasTouch && (e.button === 2 || e.which === 3)) { + return; + } + + //Event has already fired in other scope. + if (e.uiTreeDragging || (e.originalEvent && e.originalEvent.uiTreeDragging)) { + return; + } + + //The node being dragged. + var eventElm = angular.element(e.target), + isHandleChild, + cloneElm, + eventElmTagName, + tagName, + eventObj, + tdElm, + hStyle, + isTreeNode, + isTreeNodeHandle; + + //If the target element is a child element of a ui-tree-handle, + // use the containing handle element as target element. + isHandleChild = UiTreeHelper.treeNodeHandlerContainerOfElement(eventElm); + if (isHandleChild) { + eventElm = angular.element(isHandleChild); + } + + cloneElm = element.clone(); + isTreeNode = UiTreeHelper.elementIsTreeNode(eventElm); + isTreeNodeHandle = UiTreeHelper.elementIsTreeNodeHandle(eventElm); + + //If we are not triggering mousedown on our uiTree or any of it's parts, return. + if (!isTreeNode && !isTreeNodeHandle) { + return; + } + + //If we are not triggering mousedown on our uiTree or any of it's parts, return. + if (isTreeNode && UiTreeHelper.elementContainsTreeNodeHandler(eventElm)) { + return; + } + + //Dragging not allowed on inputs or buttons. + eventElmTagName = eventElm.prop('tagName').toLowerCase(); + if (eventElmTagName == 'input' || + eventElmTagName == 'textarea' || + eventElmTagName == 'button' || + eventElmTagName == 'select') { + return; + } + + //Check if it or it's parents has a 'data-nodrag' attribute + el = angular.element(e.target); + isUiTreeRoot = el[0].attributes['ui-tree']; + while (el && el[0] && el[0] !== element && !isUiTreeRoot) { + + //Checking that I can access attributes. + if (el[0].attributes) { + isUiTreeRoot = el[0].attributes['ui-tree']; + } + + //If the node mark as `nodrag`, DONOT drag it. + if (UiTreeHelper.nodrag(el)) { + return; + } + el = el.parent(); + } + + //If users beforeDrag calback returns falsey, do not initiate. + if (!scope.beforeDrag(scope)) { + return; + } + + //Set property checked at start of function to prevent running logic again. + e.uiTreeDragging = true; + if (e.originalEvent) { + e.originalEvent.uiTreeDragging = true; + } + e.preventDefault(); + + //Get original event if TouchEvent. + eventObj = UiTreeHelper.eventObj(e); + + //Set boolean used to specify beginning of move. + firstMoving = true; + + //Setting drag info properties and methods in scope of node being moved. + dragInfo = UiTreeHelper.dragInfo(scope); + + //Setting original tree to adjust horizontal behavior in drag move. + treeOfOrigin = dragInfo.source.$treeScope.$id; + + //Determine tage name of element ui-tree-node is on. + tagName = element.prop('tagName'); + + if (tagName.toLowerCase() === 'tr') { + + //Create a new table column as placeholder. + placeElm = angular.element($window.document.createElement(tagName)); + + //Create a column placeholder and set colspan to whole row length. + tdElm = angular.element($window.document.createElement('td')) + .addClass(config.placeholderClass) + .attr('colspan', element[0].children.length); + placeElm.append(tdElm); + } else { + + //If not a table just duplicate element and add placeholder class. + placeElm = angular.element($window.document.createElement(tagName)) + .addClass(config.placeholderClass); + } + + //Create a hidden placeholder and add class from config. + hiddenPlaceElm = angular.element($window.document.createElement(tagName)); + if (config.hiddenClass) { + hiddenPlaceElm.addClass(config.hiddenClass); + } + + //Getting starting position of element being moved. + pos = UiTreeHelper.positionStarted(eventObj, element); + placeElm.css('height', element.prop('offsetHeight') + 'px'); + + //Creating drag element to represent node. + dragElm = angular.element($window.document.createElement(scope.$parentNodesScope.$element.prop('tagName'))) + .addClass(scope.$parentNodesScope.$element.attr('class')).addClass(config.dragClass); + dragElm.css('width', UiTreeHelper.width(element) + 'px'); + dragElm.css('z-index', 9999); + + //Prevents cursor to change rapidly in Opera 12.16 and IE when dragging an element. + hStyle = (element[0].querySelector('.angular-ui-tree-handle') || element[0]).currentStyle; + if (hStyle) { + document.body.setAttribute('ui-tree-cursor', $document.find('body').css('cursor') || ''); + $document.find('body').css({'cursor': hStyle.cursor + '!important'}); + } + + //If tree is sourceOnly (noDragDrop) don't show placeholder when moving about it. + if (scope.sourceOnly) { + placeElm.css('display', 'none'); + } + + //Insert placeholder. + element.after(placeElm); + element.after(hiddenPlaceElm); + if (dragInfo.isClone() && scope.sourceOnly) { + dragElm.append(cloneElm); + } else { + dragElm.append(element); + } + + //Create drag element. + $document.find('body').append(dragElm); + + //Set drag elements position on screen. + dragElm.css({ + 'left': eventObj.pageX - pos.offsetX + 'px', + 'top': eventObj.pageY - pos.offsetY + 'px' + }); + elements = { + placeholder: placeElm, + dragging: dragElm + }; + + //Create all drag/move bindings. + bindDragMoveEvents(); + + //Fire dragStart callback. + scope.$apply(function () { + scope.$treeScope.$callbacks.dragStart(dragInfo.eventArgs(elements, pos)); + }); + + //Get bounds of document. + document_height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); + document_width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth); + }; + + dragMove = function (e) { + var eventObj = UiTreeHelper.eventObj(e), + prev, + next, + leftElmPos, + topElmPos, + top_scroll, + bottom_scroll, + scrollContainerElmRect, + target, + targetX, + targetY, + displayElm, + targetNode, + targetElm, + isEmpty, + scrollDownBy, + scrollUpBy, + targetOffset, + targetBefore, + moveWithinTree, + targetBeforeBuffer, + targetHeight, + targetChildElm, + targetChildHeight, + isDropzone; + + //If check ensures that drag element was created. + if (dragElm) { + e.preventDefault(); + + //Deselect anything (text, etc.) that was selected when move began. + if ($window.getSelection) { + $window.getSelection().removeAllRanges(); + } else if ($window.document.selection) { + $window.document.selection.empty(); + } + + //Get top left positioning of element being moved. + leftElmPos = eventObj.pageX - pos.offsetX; + topElmPos = eventObj.pageY - pos.offsetY; + + //dragElm can't leave the screen on the left. + if (leftElmPos < 0) { + leftElmPos = 0; + } + + //dragElm can't leave the screen on the top. + if (topElmPos < 0) { + topElmPos = 0; + } + + //dragElm can't leave the screen on the bottom. + if ((topElmPos + 10) > document_height) { + topElmPos = document_height - 10; + } + + //dragElm can't leave the screen on the right. + if ((leftElmPos + 10) > document_width) { + leftElmPos = document_width - 10; + } + + //Updating element being moved css. + dragElm.css({ + 'left': leftElmPos + 'px', + 'top': topElmPos + 'px' + }); + + if (scrollContainerElm) { + //Getting position to top and bottom of container element. + scrollContainerElmRect = scrollContainerElm.getBoundingClientRect(); + top_scroll = scrollContainerElm.scrollTop; + bottom_scroll = top_scroll + scrollContainerElm.clientHeight; + + //To scroll down if cursor y-position is greater than the bottom position of the container vertical scroll + if (scrollContainerElmRect.bottom < eventObj.clientY && bottom_scroll < scrollContainerElm.scrollHeight) { + scrollDownBy = Math.min(scrollContainerElm.scrollHeight - bottom_scroll, 10); + scrollContainerElm.scrollTop += scrollDownBy; + } + + //To scroll top if cursor y-position is less than the top position of the container vertical scroll + if (scrollContainerElmRect.top > eventObj.clientY && top_scroll > 0) { + scrollUpBy = Math.min(top_scroll, 10); + scrollContainerElm.scrollTop -= scrollUpBy; + } + } else { + //Getting position to top and bottom of page. + top_scroll = window.pageYOffset || $window.document.documentElement.scrollTop; + bottom_scroll = top_scroll + (window.innerHeight || $window.document.clientHeight || $window.document.clientHeight); + + //To scroll down if cursor y-position is greater than the bottom position of the window vertical scroll + if (bottom_scroll < eventObj.pageY && bottom_scroll < document_height) { + scrollDownBy = Math.min(document_height - bottom_scroll, 10); + window.scrollBy(0, scrollDownBy); + } + + //To scroll top if cursor y-position is less than the top position of the window vertical scroll + if (top_scroll > eventObj.pageY) { + scrollUpBy = Math.min(top_scroll, 10); + window.scrollBy(0, -scrollUpBy); + } + } + + //Calling service to update position coordinates based on move. + UiTreeHelper.positionMoved(e, pos, firstMoving); + if (firstMoving) { + firstMoving = false; + return; + } + + //Setting X point for elementFromPoint. + targetX = eventObj.pageX - ($window.pageXOffset || + $window.document.body.scrollLeft || + $window.document.documentElement.scrollLeft) - + ($window.document.documentElement.clientLeft || 0); + + targetY = eventObj.pageY - ($window.pageYOffset || + $window.document.body.scrollTop || + $window.document.documentElement.scrollTop) - + ($window.document.documentElement.clientTop || 0); + + //Select the drag target. Because IE does not support CSS 'pointer-events: none', it will always + // pick the drag element itself as the target. To prevent this, we hide the drag element while + // selecting the target. + if (angular.isFunction(dragElm.hide)) { + dragElm.hide(); + } else { + displayElm = dragElm[0].style.display; + dragElm[0].style.display = 'none'; + } + + //When using elementFromPoint() inside an iframe, you have to call + // elementFromPoint() twice to make sure IE8 returns the correct value + //MDN: The elementFromPoint() method of the Document interface returns the topmost element at the specified coordinates. + $window.document.elementFromPoint(targetX, targetY); + + //Set target element (element in specified x/y coordinates). + targetElm = angular.element($window.document.elementFromPoint(targetX, targetY)); + + //If the target element is a child element of a ui-tree-handle, + // use the containing handle element as target element + isHandleChild = UiTreeHelper.treeNodeHandlerContainerOfElement(targetElm); + if (isHandleChild) { + targetElm = angular.element(isHandleChild); + } + + if (angular.isFunction(dragElm.show)) { + dragElm.show(); + } else { + dragElm[0].style.display = displayElm; + } + + //Assigning scope to target you are moving draggable over. + if (UiTreeHelper.elementIsTree(targetElm)) { + targetNode = targetElm.controller('uiTree').scope; + } else if (UiTreeHelper.elementIsTreeNodeHandle(targetElm)) { + targetNode = targetElm.controller('uiTreeHandle').scope; + } else if (UiTreeHelper.elementIsTreeNode(targetElm)) { + targetNode = targetElm.controller('uiTreeNode').scope; + } else if (UiTreeHelper.elementIsTreeNodes(targetElm)) { + targetNode = targetElm.controller('uiTreeNodes').scope; + } else if (UiTreeHelper.elementIsPlaceholder(targetElm)) { + targetNode = targetElm.controller('uiTreeNodes').scope; + } else if (UiTreeHelper.elementIsDropzone(targetElm)) { + targetNode = targetElm.controller('uiTree').scope; + isDropzone = true; + } else if (targetElm.controller('uiTreeNode')) { + //Is a child element of a node. + targetNode = targetElm.controller('uiTreeNode').scope; + } + + moveWithinTree = (targetNode && targetNode.$treeScope && targetNode.$treeScope.$id && targetNode.$treeScope.$id === treeOfOrigin); + + /* (jcarter) Notes to developers: + * pos.dirAx is either 0 or 1 + * 1 means horizontal movement is happening + * 0 means vertical movement is happening + */ + + // Move nodes up and down in nesting level. + if (moveWithinTree && pos.dirAx) { + + // increase horizontal level if previous sibling exists and is not collapsed + // example 1.1.1 becomes 1.2 + if (pos.distX > 0) { + prev = dragInfo.prev(); + if (prev && !prev.collapsed + && prev.accept(scope, prev.childNodesCount())) { + prev.$childNodesScope.$element.append(placeElm); + dragInfo.moveTo(prev.$childNodesScope, prev.childNodes(), prev.childNodesCount()); + } + } + + // decrease horizontal level + // example 1.2 become 1.1.1 + if (pos.distX < 0) { + // we can't decrease a level if an item preceeds the current one + next = dragInfo.next(); + if (!next) { + target = dragInfo.parentNode(); // As a sibling of it's parent node + if (target + && target.$parentNodesScope.accept(scope, target.index() + 1)) { + target.$element.after(placeElm); + dragInfo.moveTo(target.$parentNodesScope, target.siblings(), target.index() + 1); + } + } + } + } else { //Either in origin tree and moving horizontally OR you are moving within a new tree. + + //Check it's new position. + isEmpty = false; + + //Exit if target is not a uiTree or child of one. + if (!targetNode) { + return; + } + + //Show the placeholder if it was hidden for nodrop-enabled and this is a new tree + if (targetNode.$treeScope && !targetNode.$parent.nodropEnabled && !targetNode.$treeScope.nodropEnabled) { + placeElm.css('display', ''); + } + + //Set whether target tree is empty or not. + if (targetNode.$type === 'uiTree' && targetNode.dragEnabled) { + isEmpty = targetNode.isEmpty(); + } + + //If target is a handle set new target to handle's node. + if (targetNode.$type === 'uiTreeHandle') { + targetNode = targetNode.$nodeScope; + } + + //Check if it is a uiTreeNode or it's an empty tree or it's a dropzone. + if (targetNode.$type !== 'uiTreeNode' && !isEmpty && !isDropzone) { + + // Allow node to return to its original position if no longer hovering over target + if (config.appendChildOnHover) { + next = dragInfo.next(); + if (!next && unhover) { + target = dragInfo.parentNode(); + target.$element.after(placeElm); + dragInfo.moveTo(target.$parentNodesScope, target.siblings(), target.index() + 1); + unhover = false; + } + } + return; + } + + //If placeholder move from empty tree, reset it. + if (treeScope && placeElm.parent()[0] != treeScope.$element[0]) { + treeScope.resetEmptyElement(); + treeScope.resetDropzoneElement(); + treeScope = null; + } + + //It's an empty tree + if (isEmpty) { + treeScope = targetNode; + if (targetNode.$nodesScope.accept(scope, 0)) { + dragInfo.moveTo(targetNode.$nodesScope, targetNode.$nodesScope.childNodes(), 0); + } + //It's a dropzone + } else if (isDropzone) { + treeScope = targetNode; + if (targetNode.$nodesScope.accept(scope, targetNode.$nodesScope.childNodes().length)) { + dragInfo.moveTo(targetNode.$nodesScope, targetNode.$nodesScope.childNodes(), targetNode.$nodesScope.childNodes().length); + } + //Not empty and drag enabled. + } else if (targetNode.dragEnabled()) { + + //Setting/Resetting data for exanding on hover. + if (angular.isDefined(scope.expandTimeoutOn) && scope.expandTimeoutOn !== targetNode.id) { + $timeout.cancel(scope.expandTimeout); + delete scope.expandTimeout; + delete scope.expandTimeoutOn; + + scope.$callbacks.expandTimeoutCancel(); + } + + //Determining if expansion is needed. + if (targetNode.collapsed) { + if (scope.expandOnHover === true || (angular.isNumber(scope.expandOnHover) && scope.expandOnHover === 0)) { + targetNode.collapsed = false; + targetNode.$treeScope.$callbacks.toggle(false, targetNode); + } else if (scope.expandOnHover !== false && angular.isNumber(scope.expandOnHover) && scope.expandOnHover > 0) { + + //Triggering expansion. + if (angular.isUndefined(scope.expandTimeoutOn)) { + scope.expandTimeoutOn = targetNode.$id; + + scope.$callbacks.expandTimeoutStart(); + scope.expandTimeout = $timeout(function() + { + scope.$callbacks.expandTimeoutEnd(); + targetNode.collapsed = false; + targetNode.$treeScope.$callbacks.toggle(false, targetNode); + }, scope.expandOnHover); + } + } + } + + //Get the element of ui-tree-node + targetElm = targetNode.$element; + targetOffset = UiTreeHelper.offset(targetElm); + targetHeight = UiTreeHelper.height(targetElm); + targetChildElm = targetNode.$childNodesScope ? targetNode.$childNodesScope.$element : null; + targetChildHeight = targetChildElm ? UiTreeHelper.height(targetChildElm) : 0; + targetHeight -= targetChildHeight; + targetBeforeBuffer = config.appendChildOnHover ? targetHeight * 0.25 : UiTreeHelper.height(targetElm) / 2; + targetBefore = eventObj.pageY < (targetOffset.top + targetBeforeBuffer); + + if (targetNode.$parentNodesScope.accept(scope, targetNode.index())) { + if (targetBefore) { + targetElm[0].parentNode.insertBefore(placeElm[0], targetElm[0]); + dragInfo.moveTo(targetNode.$parentNodesScope, targetNode.siblings(), targetNode.index()); + } else { + // Try to append as a child if dragged upwards onto targetNode + if (config.appendChildOnHover && targetNode.accept(scope, targetNode.childNodesCount())) { + targetNode.$childNodesScope.$element.prepend(placeElm); + dragInfo.moveTo(targetNode.$childNodesScope, targetNode.childNodes(), 0); + unhover = true; + } else { + targetElm.after(placeElm); + dragInfo.moveTo(targetNode.$parentNodesScope, targetNode.siblings(), targetNode.index() + 1); + } + } + + //We have to check if it can add the dragging node as a child. + } else if (!targetBefore && targetNode.accept(scope, targetNode.childNodesCount())) { + targetNode.$childNodesScope.$element.append(placeElm); + dragInfo.moveTo(targetNode.$childNodesScope, targetNode.childNodes(), targetNode.childNodesCount()); + } + } + } + + //Triggering dragMove callback. + scope.$apply(function () { + scope.$treeScope.$callbacks.dragMove(dragInfo.eventArgs(elements, pos)); + }); + } + }; + + dragEnd = function (e) { + + var dragEventArgs = dragInfo.eventArgs(elements, pos); + + e.preventDefault(); + + //TODO(jcarter): Is dragStart need to be unbound? + unbindDragMoveEvents(); + + //This cancel the collapse/expand login running. + $timeout.cancel(scope.expandTimeout); + + scope.$treeScope.$apply(function () { + $q.when(scope.$treeScope.$callbacks.beforeDrop(dragEventArgs)) + + //Promise resolved (or callback didn't return false) + .then(function (allowDrop) { + if (allowDrop !== false && scope.$$allowNodeDrop) { + //Node drop accepted. + dragInfo.apply(); + + //Fire the dropped callback only if the move was successful. + scope.$treeScope.$callbacks.dropped(dragEventArgs); + } else { + //Drop canceled - revert the node to its original position. + bindDragStartEvents(); + } + }) + + //Promise rejected - revert the node to its original position. + .catch(function () { + bindDragStartEvents(); + }) + .finally(function () { + + //Replace placeholder with newly dropped element. + hiddenPlaceElm.replaceWith(scope.$element); + placeElm.remove(); + + //Remove drag element if still in DOM. + if (dragElm) { + dragElm.remove(); + dragElm = null; + } + + //Fire dragStope callback. + scope.$treeScope.$callbacks.dragStop(dragEventArgs); + scope.$$allowNodeDrop = false; + dragInfo = null; + + //Restore cursor in Opera 12.16 and IE + var oldCur = document.body.getAttribute('ui-tree-cursor'); + if (oldCur !== null) { + $document.find('body').css({'cursor': oldCur}); + document.body.removeAttribute('ui-tree-cursor'); + } + }); + }); + }; + + dragStartEvent = function (e) { + if (scope.dragEnabled()) { + dragStart(e); + } + }; + + dragMoveEvent = function (e) { + dragMove(e); + }; + + dragEndEvent = function (e) { + scope.$$allowNodeDrop = true; + dragEnd(e); + }; + + dragCancelEvent = function (e) { + dragEnd(e); + }; + + dragDelay = (function () { + var to; + + return { + exec: function (fn, ms) { + if (!ms) { + ms = 0; + } + this.cancel(); + to = $timeout(fn, ms); + }, + cancel: function () { + $timeout.cancel(to); + } + }; + })(); + + keydownHandler = function (e) { + if (e.keyCode === 27) { + dragEndEvent(e); + } + }; + + /** + * Binds the mouse/touch events to enable drag start for this node. + */ + //This is outside of bindDragMoveEvents because of the potential for a delay setting. + bindDragStartEvents = function () { + element.bind('touchstart mousedown', function (e) { + //Don't call drag delay if no delay was specified. + if (scope.dragDelay > 0) { + dragDelay.exec(function () { + dragStartEvent(e); + }, scope.dragDelay); + } else { + dragStartEvent(e); + } + }); + element.bind('touchend touchcancel mouseup', function () { + if (scope.dragDelay > 0) { + dragDelay.cancel(); + } + }); + }; + bindDragStartEvents(); + + /** + * Binds mouse/touch events that handle moving/dropping this dragged node + */ + bindDragMoveEvents = function () { + angular.element($document).bind('touchend', dragEndEvent); + angular.element($document).bind('touchcancel', dragEndEvent); + angular.element($document).bind('touchmove', dragMoveEvent); + angular.element($document).bind('mouseup', dragEndEvent); + angular.element($document).bind('mousemove', dragMoveEvent); + angular.element($document).bind('mouseleave', dragCancelEvent); + angular.element($document).bind('keydown', keydownHandler); + }; + + /** + * Unbinds mouse/touch events that handle moving/dropping this dragged node. + */ + unbindDragMoveEvents = function () { + angular.element($document).unbind('touchend', dragEndEvent); + angular.element($document).unbind('touchcancel', dragEndEvent); + angular.element($document).unbind('touchmove', dragMoveEvent); + angular.element($document).unbind('mouseup', dragEndEvent); + angular.element($document).unbind('mousemove', dragMoveEvent); + angular.element($document).unbind('mouseleave', dragCancelEvent); + angular.element($document).unbind('keydown', keydownHandler); + }; + } + }; + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + .directive('uiTreeNodes', ['treeConfig', '$window', + function (treeConfig) { + return { + require: ['ngModel', '?^uiTreeNode', '^uiTree'], + restrict: 'A', + scope: true, + controller: 'TreeNodesController', + link: function (scope, element, attrs, controllersArr) { + + var config = {}, + ngModel = controllersArr[0], + treeNodeCtrl = controllersArr[1], + treeCtrl = controllersArr[2]; + + angular.extend(config, treeConfig); + if (config.nodesClass) { + element.addClass(config.nodesClass); + } + + if (treeNodeCtrl) { + treeNodeCtrl.scope.$childNodesScope = scope; + scope.$nodeScope = treeNodeCtrl.scope; + } else { + // find the root nodes if there is no parent node and have a parent ui-tree + treeCtrl.scope.$nodesScope = scope; + } + scope.$treeScope = treeCtrl.scope; + + if (ngModel) { + ngModel.$render = function () { + scope.$modelValue = ngModel.$modelValue; + }; + } + + scope.$watch(function () { + return attrs.maxDepth; + }, function (val) { + if ((typeof val) == 'number') { + scope.maxDepth = val; + } + }); + + scope.$watch(function () { + return attrs.nodropEnabled; + }, function (newVal) { + if ((typeof newVal) != 'undefined') { + scope.nodropEnabled = true; + } + }, true); + + } + }; + } + ]); +})(); + +(function () { + 'use strict'; + + angular.module('ui.tree') + + /** + * @ngdoc service + * @name ui.tree.service:UiTreeHelper + * @requires ng.$document + * @requires ng.$window + * + * @description + * angular-ui-tree. + */ + .factory('UiTreeHelper', ['$document', '$window', 'treeConfig', + function ($document, $window, treeConfig) { + return { + + /** + * A hashtable used to storage data of nodes + * @type {Object} + */ + nodesData: {}, + + setNodeAttribute: function (scope, attrName, val) { + if (!scope.$modelValue) { + return null; + } + var data = this.nodesData[scope.$modelValue.$$hashKey]; + if (!data) { + data = {}; + this.nodesData[scope.$modelValue.$$hashKey] = data; + } + data[attrName] = val; + }, + + getNodeAttribute: function (scope, attrName) { + if (!scope.$modelValue) { + return null; + } + var data = this.nodesData[scope.$modelValue.$$hashKey]; + if (data) { + return data[attrName]; + } + return null; + }, + + /** + * @ngdoc method + * @methodOf ui.tree.service:$nodrag + * @param {Object} targetElm angular element + * @return {Bool} check if the node can be dragged. + */ + nodrag: function (targetElm) { + if (typeof targetElm.attr('data-nodrag') != 'undefined') { + return targetElm.attr('data-nodrag') !== 'false'; + } + return false; + }, + + /** + * Get the event object for touches. + * + * @param {MouseEvent|TouchEvent} e MouseEvent or TouchEvent that kicked off dragX method. + * @return {MouseEvent|TouchEvent} Object returned as original event object. + */ + eventObj: function (e) { + var obj = e; + if (e.targetTouches !== undefined) { + //Set obj equal to the first Touch object in the TouchList. + obj = e.targetTouches.item(0); + //Logic to set obj to original TouchEvent. + } else if (e.originalEvent !== undefined && e.originalEvent.targetTouches !== undefined) { + obj = e.originalEvent.targetTouches.item(0); + } + return obj; + }, + + /** + * Generate object used to store data about node being moved. + * + * {angular.$scope} node Scope of the node that is being moved. + */ + dragInfo: function (node) { + return { + source: node, + sourceInfo: { + cloneModel: node.$treeScope.cloneEnabled === true ? angular.copy(node.$modelValue) : undefined, + nodeScope: node, + index: node.index(), + nodesScope: node.$parentNodesScope + }, + index: node.index(), + + //Slice(0) just duplicates an array. + siblings: node.siblings().slice(0), + parent: node.$parentNodesScope, + + //Reset parent to source parent. + resetParent: function() { + this.parent = node.$parentNodesScope; + }, + + //Move the node to a new position, determining where the node will be inserted to when dropped happens here. + moveTo: function (parent, siblings, index) { + this.parent = parent; + + //Duplicate siblings array. + this.siblings = siblings.slice(0); + + //If source node is in the target nodes + var i = this.siblings.indexOf(this.source); + if (i > -1) { + this.siblings.splice(i, 1); + if (this.source.index() < index) { + index--; + } + } + + this.siblings.splice(index, 0, this.source); + this.index = index; + }, + + //Get parent nodes nodeScope. + parentNode: function () { + return this.parent.$nodeScope; + }, + + //Get previous sibling node. + prev: function () { + if (this.index > 0) { + return this.siblings[this.index - 1]; + } + + return null; + }, + + //Get next sibling node. + next: function () { + if (this.index < this.siblings.length - 1) { + return this.siblings[this.index + 1]; + } + + return null; + }, + + //Return what cloneEnabled is set to on uiTree. + isClone: function () { + return this.source.$treeScope.cloneEnabled === true; + }, + + //Returns a copy of node passed in. + clonedNode: function (node) { + return angular.copy(node); + }, + + //Returns true if parent or index have changed (move happened within any uiTree). + isDirty: function () { + return this.source.$parentNodesScope != this.parent || + this.source.index() != this.index; + }, + + //Return whether node has a new parent (set on moveTo method). + isForeign: function () { + return this.source.$treeScope !== this.parent.$treeScope; + }, + + //Sets arguments passed to user callbacks. + eventArgs: function (elements, pos) { + return { + source: this.sourceInfo, + dest: { + index: this.index, + nodesScope: this.parent + }, + elements: elements, + pos: pos + }; + }, + + //Method that actually manipulates the node being moved. + apply: function () { + + var nodeData = this.source.$modelValue; + + //Nodrop enabled on tree or parent + if (this.parent.nodropEnabled || this.parent.$treeScope.nodropEnabled) { + return; + } + + //Node was dropped in the same place - do nothing. + if (!this.isDirty()) { + return; + } + + //CloneEnabled and cross-tree so copy and do not remove from source. + if (this.isClone() && this.isForeign()) { + this.parent.insertNode(this.index, this.sourceInfo.cloneModel); + //Any other case, remove and reinsert. + } else { + this.source.remove(); + this.parent.insertNode(this.index, nodeData); + } + } + }; + }, + + /** + * @ngdoc method + * @name ui.tree#height + * @methodOf ui.tree.service:UiTreeHelper + * + * @description + * Get the height of an element. + * + * @param {Object} element Angular element. + * @returns {String} Height + */ + height: function (element) { + return element.prop('scrollHeight'); + }, + + /** + * @ngdoc method + * @name ui.tree#width + * @methodOf ui.tree.service:UiTreeHelper + * + * @description + * Get the width of an element. + * + * @param {Object} element Angular element. + * @returns {String} Width + */ + width: function (element) { + return element.prop('scrollWidth'); + }, + + /** + * @ngdoc method + * @name ui.tree#offset + * @methodOf ui.nestedSortable.service:UiTreeHelper + * + * @description + * Get the offset values of an element. + * + * @param {Object} element Angular element. + * @returns {Object} Object with properties width, height, top and left + */ + offset: function (element) { + var boundingClientRect = element[0].getBoundingClientRect(); + + return { + width: element.prop('offsetWidth'), + height: element.prop('offsetHeight'), + top: boundingClientRect.top + ($window.pageYOffset || $document[0].body.scrollTop || $document[0].documentElement.scrollTop), + left: boundingClientRect.left + ($window.pageXOffset || $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft) + }; + }, + + /** + * @ngdoc method + * @name ui.tree#positionStarted + * @methodOf ui.tree.service:UiTreeHelper + * + * @description + * Get the start position of the target element according to the provided event properties. + * + * @param {Object} e Event + * @param {Object} target Target element + * @returns {Object} Object with properties offsetX, offsetY, startX, startY, nowX and dirX. + */ + positionStarted: function (e, target) { + var pos = {}, + pageX = e.pageX, + pageY = e.pageY; + + //Check to set correct data for TouchEvents + if (e.originalEvent && e.originalEvent.touches && (e.originalEvent.touches.length > 0)) { + pageX = e.originalEvent.touches[0].pageX; + pageY = e.originalEvent.touches[0].pageY; + } + pos.offsetX = pageX - this.offset(target).left; + pos.offsetY = pageY - this.offset(target).top; + pos.startX = pos.lastX = pageX; + pos.startY = pos.lastY = pageY; + pos.nowX = pos.nowY = pos.distX = pos.distY = pos.dirAx = 0; + pos.dirX = pos.dirY = pos.lastDirX = pos.lastDirY = pos.distAxX = pos.distAxY = 0; + return pos; + }, + + positionMoved: function (e, pos, firstMoving) { + + var pageX = e.pageX, + pageY = e.pageY, + newAx; + + //If there are multiple touch points, choose one to use as X and Y. + if (e.originalEvent && e.originalEvent.touches && (e.originalEvent.touches.length > 0)) { + pageX = e.originalEvent.touches[0].pageX; + pageY = e.originalEvent.touches[0].pageY; + } + + //Mouse position last event. + pos.lastX = pos.nowX; + pos.lastY = pos.nowY; + + //Mouse position this event. + pos.nowX = pageX; + pos.nowY = pageY; + + //Distance mouse moved between events. + pos.distX = pos.nowX - pos.lastX; + pos.distY = pos.nowY - pos.lastY; + + //Direction mouse was moving. + pos.lastDirX = pos.dirX; + pos.lastDirY = pos.dirY; + + //Direction mouse is now moving (on both axis). + pos.dirX = pos.distX === 0 ? 0 : pos.distX > 0 ? 1 : -1; + pos.dirY = pos.distY === 0 ? 0 : pos.distY > 0 ? 1 : -1; + + //Axis mouse is now moving on. + newAx = Math.abs(pos.distX) > Math.abs(pos.distY) ? 1 : 0; + + //Do nothing on first move. + if (firstMoving) { + pos.dirAx = newAx; + pos.moving = true; + return; + } + + //Calc distance moved on this axis (and direction). + if (pos.dirAx !== newAx) { + pos.distAxX = 0; + pos.distAxY = 0; + } else { + pos.distAxX += Math.abs(pos.distX); + if (pos.dirX !== 0 && pos.dirX !== pos.lastDirX) { + pos.distAxX = 0; + } + pos.distAxY += Math.abs(pos.distY); + if (pos.dirY !== 0 && pos.dirY !== pos.lastDirY) { + pos.distAxY = 0; + } + } + pos.dirAx = newAx; + }, + + elementIsTreeNode: function (element) { + return typeof element.attr('ui-tree-node') !== 'undefined'; + }, + + elementIsTreeNodeHandle: function (element) { + return typeof element.attr('ui-tree-handle') !== 'undefined'; + }, + elementIsTree: function (element) { + return typeof element.attr('ui-tree') !== 'undefined'; + }, + elementIsTreeNodes: function (element) { + return typeof element.attr('ui-tree-nodes') !== 'undefined'; + }, + elementIsPlaceholder: function (element) { + return element.hasClass(treeConfig.placeholderClass); + }, + elementIsDropzone: function (element) { + return element.hasClass(treeConfig.dropzoneClass); + }, + elementContainsTreeNodeHandler: function (element) { + return element[0].querySelectorAll('[ui-tree-handle]').length >= 1; + }, + treeNodeHandlerContainerOfElement: function (element) { + return findFirstParentElementWithAttribute('ui-tree-handle', element[0]); + } + }; + } + ]); + + // TODO: optimize this loop + //(Jcarter): Suggest adding a parent element property on uiTree, then all these bubble + // to can trigger to stop when they reach the parent. + function findFirstParentElementWithAttribute(attributeName, childObj) { + //Undefined if the mouse leaves the browser window + if (childObj === undefined) { + return null; + } + var testObj = childObj.parentNode, + count = 1, + //Check for setAttribute due to exception thrown by Firefox when a node is dragged outside the browser window + res = (typeof testObj.setAttribute === 'function' && testObj.hasAttribute(attributeName)) ? testObj : null; + while (testObj && typeof testObj.setAttribute === 'function' && !testObj.hasAttribute(attributeName)) { + testObj = testObj.parentNode; + res = testObj; + //Stop once we reach top of page. + if (testObj === document.documentElement) { + res = null; + break; + } + count++; + } + return res; + } + +})(); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.min.css b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.min.css new file mode 100644 index 0000000..5ae2166 --- /dev/null +++ b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.min.css @@ -0,0 +1 @@ +.angular-ui-tree-dropzone,.angular-ui-tree-empty{border:1px dashed #bbb;min-height:100px;background-color:#e5e5e5;background-image:-webkit-linear-gradient(45deg,#fff 25%,transparent 0,transparent 75%,#fff 0,#fff),-webkit-linear-gradient(45deg,#fff 25%,transparent 0,transparent 75%,#fff 0,#fff);background-image:linear-gradient(45deg,#fff 25%,transparent 0,transparent 75%,#fff 0,#fff),linear-gradient(45deg,#fff 25%,transparent 0,transparent 75%,#fff 0,#fff);background-size:60px 60px;background-position:0 0,30px 30px}.angular-ui-tree-empty{pointer-events:none}.angular-ui-tree-nodes{position:relative;margin:0;padding:0;list-style:none}.angular-ui-tree-nodes .angular-ui-tree-nodes{padding-left:20px}.angular-ui-tree-node,.angular-ui-tree-placeholder{position:relative;margin:0;padding:0;min-height:20px;line-height:20px}.angular-ui-tree-hidden{display:none}.angular-ui-tree-placeholder{margin:10px;padding:0;min-height:30px}.angular-ui-tree-handle{cursor:move;text-decoration:none;font-weight:700;box-sizing:border-box;min-height:20px;line-height:20px}.angular-ui-tree-drag{position:absolute;pointer-events:none;z-index:999;opacity:.8}.angular-ui-tree-drag .tree-node-content{margin-top:0} \ No newline at end of file diff --git a/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.min.js b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.min.js new file mode 100644 index 0000000..71aa61e --- /dev/null +++ b/src/main/resources/static/module/angular-ui-tree/angular-ui-tree.min.js @@ -0,0 +1,6 @@ +/** + * @license Angular UI Tree v2.22.5 + * (c) 2010-2017. https://github.com/angular-ui-tree/angular-ui-tree + * License: MIT + */ +!function(){"use strict";angular.module("ui.tree",[]).constant("treeConfig",{treeClass:"angular-ui-tree",emptyTreeClass:"angular-ui-tree-empty",dropzoneClass:"angular-ui-tree-dropzone",hiddenClass:"angular-ui-tree-hidden",nodesClass:"angular-ui-tree-nodes",nodeClass:"angular-ui-tree-node",handleClass:"angular-ui-tree-handle",placeholderClass:"angular-ui-tree-placeholder",dragClass:"angular-ui-tree-drag",dragThreshold:3,defaultCollapsed:!1,appendChildOnHover:!0})}(),function(){"use strict";angular.module("ui.tree").controller("TreeHandleController",["$scope","$element",function(e,n){this.scope=e,e.$element=n,e.$nodeScope=null,e.$type="uiTreeHandle"}])}(),function(){"use strict";angular.module("ui.tree").controller("TreeNodeController",["$scope","$element",function(e,n){function t(e){if(!e)return 0;var n,o,l,r=0,a=e.childNodes();if(!a||0===a.length)return 0;for(l=a.length-1;l>=0;l--)n=a[l],o=1+t(n),r=Math.max(r,o);return r}this.scope=e,e.$element=n,e.$modelValue=null,e.$parentNodeScope=null,e.$childNodesScope=null,e.$parentNodesScope=null,e.$treeScope=null,e.$handleScope=null,e.$type="uiTreeNode",e.$$allowNodeDrop=!1,e.collapsed=!1,e.expandOnHover=!1,e.init=function(t){var o=t[0];e.$treeScope=t[1]?t[1].scope:null,e.$parentNodeScope=o.scope.$nodeScope,e.$modelValue=o.scope.$modelValue[e.$index],e.$parentNodesScope=o.scope,o.scope.initSubNode(e),n.on("$destroy",function(){o.scope.destroySubNode(e)})},e.index=function(){return e.$parentNodesScope.$modelValue.indexOf(e.$modelValue)},e.dragEnabled=function(){return!(e.$treeScope&&!e.$treeScope.dragEnabled)},e.isSibling=function(n){return e.$parentNodesScope==n.$parentNodesScope},e.isChild=function(n){var t=e.childNodes();return t&&t.indexOf(n)>-1},e.prev=function(){var n=e.index();return n>0?e.siblings()[n-1]:null},e.siblings=function(){return e.$parentNodesScope.childNodes()},e.childNodesCount=function(){return e.childNodes()?e.childNodes().length:0},e.hasChild=function(){return e.childNodesCount()>0},e.childNodes=function(){return e.$childNodesScope&&e.$childNodesScope.$modelValue?e.$childNodesScope.childNodes():null},e.accept=function(n,t){return e.$childNodesScope&&e.$childNodesScope.$modelValue&&e.$childNodesScope.accept(n,t)},e.remove=function(){return e.$parentNodesScope.removeNode(e)},e.toggle=function(){e.collapsed=!e.collapsed,e.$treeScope.$callbacks.toggle(e.collapsed,e)},e.collapse=function(){e.collapsed=!0},e.expand=function(){e.collapsed=!1},e.depth=function(){var n=e.$parentNodeScope;return n?n.depth()+1:1},e.maxSubDepth=function(){return e.$childNodesScope?t(e.$childNodesScope):0}}])}(),function(){"use strict";angular.module("ui.tree").controller("TreeNodesController",["$scope","$element",function(e,n){this.scope=e,e.$element=n,e.$modelValue=null,e.$nodeScope=null,e.$treeScope=null,e.$type="uiTreeNodes",e.$nodesMap={},e.nodropEnabled=!1,e.maxDepth=0,e.cloneEnabled=!1,e.initSubNode=function(n){return n.$modelValue?void(e.$nodesMap[n.$modelValue.$$hashKey]=n):null},e.destroySubNode=function(n){return n.$modelValue?void(e.$nodesMap[n.$modelValue.$$hashKey]=null):null},e.accept=function(n,t){return e.$treeScope.$callbacks.accept(n,e,t)},e.beforeDrag=function(n){return e.$treeScope.$callbacks.beforeDrag(n)},e.isParent=function(n){return n.$parentNodesScope==e},e.hasChild=function(){return e.$modelValue.length>0},e.safeApply=function(e){var n=this.$root.$$phase;"$apply"==n||"$digest"==n?e&&"function"==typeof e&&e():this.$apply(e)},e.removeNode=function(n){var t=e.$modelValue.indexOf(n.$modelValue);return t>-1?(e.safeApply(function(){e.$modelValue.splice(t,1)[0]}),e.$treeScope.$callbacks.removed(n)):null},e.insertNode=function(n,t){e.safeApply(function(){e.$modelValue.splice(n,0,t)})},e.childNodes=function(){var n,t=[];if(e.$modelValue)for(n=0;n0&&e.depth()+n.maxSubDepth()+1>t}}])}(),function(){"use strict";angular.module("ui.tree").controller("TreeController",["$scope","$element",function(e,n){this.scope=e,e.$element=n,e.$nodesScope=null,e.$type="uiTree",e.$emptyElm=null,e.$dropzoneElm=null,e.$callbacks=null,e.dragEnabled=!0,e.emptyPlaceholderEnabled=!0,e.maxDepth=0,e.dragDelay=0,e.cloneEnabled=!1,e.nodropEnabled=!1,e.dropzoneEnabled=!1,e.isEmpty=function(){return e.$nodesScope&&e.$nodesScope.$modelValue&&0===e.$nodesScope.$modelValue.length},e.place=function(n){e.$nodesScope.$element.append(n),e.$emptyElm.remove()},this.resetEmptyElement=function(){e.$nodesScope.$modelValue&&0!==e.$nodesScope.$modelValue.length||!e.emptyPlaceholderEnabled?e.$emptyElm.remove():n.append(e.$emptyElm)},this.resetDropzoneElement=function(){e.$nodesScope.$modelValue&&0===e.$nodesScope.$modelValue.length||!e.dropzoneEnabled?e.$dropzoneElm.remove():n.append(e.$dropzoneElm)},e.resetEmptyElement=this.resetEmptyElement,e.resetDropzoneElement=this.resetDropzoneElement}])}(),function(){"use strict";angular.module("ui.tree").directive("uiTree",["treeConfig","$window",function(e,n){return{restrict:"A",scope:!0,controller:"TreeController",link:function(t,o,l,r){var a,d,i,c={accept:null,beforeDrag:null},s={};angular.extend(s,e),s.treeClass&&o.addClass(s.treeClass),"table"===o.prop("tagName").toLowerCase()?(t.$emptyElm=angular.element(n.document.createElement("tr")),d=o.find("tr"),i=d.length>0?angular.element(d).children().length:1e6,a=angular.element(n.document.createElement("td")).attr("colspan",i),t.$emptyElm.append(a)):(t.$emptyElm=angular.element(n.document.createElement("div")),t.$dropzoneElm=angular.element(n.document.createElement("div"))),s.emptyTreeClass&&t.$emptyElm.addClass(s.emptyTreeClass),s.dropzoneClass&&t.$dropzoneElm.addClass(s.dropzoneClass),t.$watch("$nodesScope.$modelValue.length",function(e){angular.isNumber(e)&&(r.resetEmptyElement(),r.resetDropzoneElement())},!0),t.$watch(l.dragEnabled,function(e){"boolean"==typeof e&&(t.dragEnabled=e)}),t.$watch(l.emptyPlaceholderEnabled,function(e){"boolean"==typeof e&&(t.emptyPlaceholderEnabled=e,r.resetEmptyElement())}),t.$watch(l.nodropEnabled,function(e){"boolean"==typeof e&&(t.nodropEnabled=e)}),t.$watch(l.dropzoneEnabled,function(e){"boolean"==typeof e&&(t.dropzoneEnabled=e,r.resetDropzoneElement())}),t.$watch(l.cloneEnabled,function(e){"boolean"==typeof e&&(t.cloneEnabled=e)}),t.$watch(l.maxDepth,function(e){"number"==typeof e&&(t.maxDepth=e)}),t.$watch(l.dragDelay,function(e){"number"==typeof e&&(t.dragDelay=e)}),c.accept=function(e,n,t){return!(n.nodropEnabled||n.$treeScope.nodropEnabled||n.outOfDepth(e))},c.beforeDrag=function(e){return!0},c.expandTimeoutStart=function(){},c.expandTimeoutCancel=function(){},c.expandTimeoutEnd=function(){},c.removed=function(e){},c.dropped=function(e){},c.dragStart=function(e){},c.dragMove=function(e){},c.dragStop=function(e){},c.beforeDrop=function(e){},c.toggle=function(e,n){},t.$watch(l.uiTree,function(e,n){angular.forEach(e,function(e,n){c[n]&&"function"==typeof e&&(c[n]=e)}),t.$callbacks=c},!0)}}}])}(),function(){"use strict";angular.module("ui.tree").directive("uiTreeHandle",["treeConfig",function(e){return{require:"^uiTreeNode",restrict:"A",scope:!0,controller:"TreeHandleController",link:function(n,t,o,l){var r={};angular.extend(r,e),r.handleClass&&t.addClass(r.handleClass),n!=l.scope&&(n.$nodeScope=l.scope,l.scope.$handleScope=n)}}}])}(),function(){"use strict";angular.module("ui.tree").directive("uiTreeNode",["treeConfig","UiTreeHelper","$window","$document","$timeout","$q",function(e,n,t,o,l,r){return{require:["^uiTreeNodes","^uiTree"],restrict:"A",controller:"TreeNodeController",link:function(a,d,i,c){var s,u,p,m,f,h,$,g,b,v,N,S,y,E,x,C,T,w,D,H,O,Y,A,X,V,k,z,M={},I="ontouchstart"in window,P=null,L=document.body,W=document.documentElement;angular.extend(M,e),M.nodeClass&&d.addClass(M.nodeClass),a.init(c),a.collapsed=!!n.getNodeAttribute(a,"collapsed")||e.defaultCollapsed,a.expandOnHover=!!n.getNodeAttribute(a,"expandOnHover"),a.scrollContainer=n.getNodeAttribute(a,"scrollContainer")||i.scrollContainer||null,a.sourceOnly=a.nodropEnabled||a.$treeScope.nodropEnabled,a.$watch(i.collapsed,function(e){"boolean"==typeof e&&(a.collapsed=e)}),a.$watch("collapsed",function(e){n.setNodeAttribute(a,"collapsed",e),i.$set("collapsed",e)}),a.$watch(i.expandOnHover,function(e){"boolean"!=typeof e&&"number"!=typeof e||(a.expandOnHover=e)}),a.$watch("expandOnHover",function(e){n.setNodeAttribute(a,"expandOnHover",e),i.$set("expandOnHover",e)}),i.$observe("scrollContainer",function(e){"string"==typeof e&&(a.scrollContainer=e)}),a.$watch("scrollContainer",function(e){n.setNodeAttribute(a,"scrollContainer",e),i.$set("scrollContainer",e),$=document.querySelector(e)}),a.$on("angular-ui-tree:collapse-all",function(){a.collapsed=!0}),a.$on("angular-ui-tree:expand-all",function(){a.collapsed=!1}),S=function(e){if((I||2!==e.button&&3!==e.which)&&!(e.uiTreeDragging||e.originalEvent&&e.originalEvent.uiTreeDragging)){var l,r,i,c,$,g,S,y,E,x=angular.element(e.target);if(l=n.treeNodeHandlerContainerOfElement(x),l&&(x=angular.element(l)),r=d.clone(),y=n.elementIsTreeNode(x),E=n.elementIsTreeNodeHandle(x),(y||E)&&!(y&&n.elementContainsTreeNodeHandler(x)||(i=x.prop("tagName").toLowerCase(),"input"==i||"textarea"==i||"button"==i||"select"==i))){for(V=angular.element(e.target),k=V[0].attributes["ui-tree"];V&&V[0]&&V[0]!==d&&!k;){if(V[0].attributes&&(k=V[0].attributes["ui-tree"]),n.nodrag(V))return;V=V.parent()}a.beforeDrag(a)&&(e.uiTreeDragging=!0,e.originalEvent&&(e.originalEvent.uiTreeDragging=!0),e.preventDefault(),$=n.eventObj(e),s=!0,u=n.dragInfo(a),z=u.source.$treeScope.$id,c=d.prop("tagName"),"tr"===c.toLowerCase()?(m=angular.element(t.document.createElement(c)),g=angular.element(t.document.createElement("td")).addClass(M.placeholderClass).attr("colspan",d[0].children.length),m.append(g)):m=angular.element(t.document.createElement(c)).addClass(M.placeholderClass),f=angular.element(t.document.createElement(c)),M.hiddenClass&&f.addClass(M.hiddenClass),p=n.positionStarted($,d),m.css("height",d.prop("offsetHeight")+"px"),h=angular.element(t.document.createElement(a.$parentNodesScope.$element.prop("tagName"))).addClass(a.$parentNodesScope.$element.attr("class")).addClass(M.dragClass),h.css("width",n.width(d)+"px"),h.css("z-index",9999),S=(d[0].querySelector(".angular-ui-tree-handle")||d[0]).currentStyle,S&&(document.body.setAttribute("ui-tree-cursor",o.find("body").css("cursor")||""),o.find("body").css({cursor:S.cursor+"!important"})),a.sourceOnly&&m.css("display","none"),d.after(m),d.after(f),u.isClone()&&a.sourceOnly?h.append(r):h.append(d),o.find("body").append(h),h.css({left:$.pageX-p.offsetX+"px",top:$.pageY-p.offsetY+"px"}),b={placeholder:m,dragging:h},O(),a.$apply(function(){a.$treeScope.$callbacks.dragStart(u.eventArgs(b,p))}),v=Math.max(L.scrollHeight,L.offsetHeight,W.clientHeight,W.scrollHeight,W.offsetHeight),N=Math.max(L.scrollWidth,L.offsetWidth,W.clientWidth,W.scrollWidth,W.offsetWidth))}}},y=function(e){var o,r,d,i,c,f,S,y,E,x,C,T,w,D,H,O,Y,A,V,k,I,L,W,q,F=n.eventObj(e);if(h){if(e.preventDefault(),t.getSelection?t.getSelection().removeAllRanges():t.document.selection&&t.document.selection.empty(),d=F.pageX-p.offsetX,i=F.pageY-p.offsetY,d<0&&(d=0),i<0&&(i=0),i+10>v&&(i=v-10),d+10>N&&(d=N-10),h.css({left:d+"px",top:i+"px"}),$?(S=$.getBoundingClientRect(),c=$.scrollTop,f=c+$.clientHeight,S.bottomF.clientY&&c>0&&(O=Math.min(c,10),$.scrollTop-=O)):(c=window.pageYOffset||t.document.documentElement.scrollTop,f=c+(window.innerHeight||t.document.clientHeight||t.document.clientHeight),fF.pageY&&(O=Math.min(c,10),window.scrollBy(0,-O))),n.positionMoved(e,p,s),s)return void(s=!1);if(E=F.pageX-(t.pageXOffset||t.document.body.scrollLeft||t.document.documentElement.scrollLeft)-(t.document.documentElement.clientLeft||0),x=F.pageY-(t.pageYOffset||t.document.body.scrollTop||t.document.documentElement.scrollTop)-(t.document.documentElement.clientTop||0),angular.isFunction(h.hide)?h.hide():(C=h[0].style.display,h[0].style.display="none"),t.document.elementFromPoint(E,x),w=angular.element(t.document.elementFromPoint(E,x)),X=n.treeNodeHandlerContainerOfElement(w),X&&(w=angular.element(X)),angular.isFunction(h.show)?h.show():h[0].style.display=C,n.elementIsTree(w)?T=w.controller("uiTree").scope:n.elementIsTreeNodeHandle(w)?T=w.controller("uiTreeHandle").scope:n.elementIsTreeNode(w)?T=w.controller("uiTreeNode").scope:n.elementIsTreeNodes(w)?T=w.controller("uiTreeNodes").scope:n.elementIsPlaceholder(w)?T=w.controller("uiTreeNodes").scope:n.elementIsDropzone(w)?(T=w.controller("uiTree").scope,q=!0):w.controller("uiTreeNode")&&(T=w.controller("uiTreeNode").scope),V=T&&T.$treeScope&&T.$treeScope.$id&&T.$treeScope.$id===z,V&&p.dirAx)p.distX>0&&(o=u.prev(),o&&!o.collapsed&&o.accept(a,o.childNodesCount())&&(o.$childNodesScope.$element.append(m),u.moveTo(o.$childNodesScope,o.childNodes(),o.childNodesCount()))),p.distX<0&&(r=u.next(),r||(y=u.parentNode(),y&&y.$parentNodesScope.accept(a,y.index()+1)&&(y.$element.after(m),u.moveTo(y.$parentNodesScope,y.siblings(),y.index()+1))));else{if(D=!1,!T)return;if(!T.$treeScope||T.$parent.nodropEnabled||T.$treeScope.nodropEnabled||m.css("display",""),"uiTree"===T.$type&&T.dragEnabled&&(D=T.isEmpty()),"uiTreeHandle"===T.$type&&(T=T.$nodeScope),"uiTreeNode"!==T.$type&&!D&&!q)return void(M.appendChildOnHover&&(r=u.next(),!r&&g&&(y=u.parentNode(),y.$element.after(m),u.moveTo(y.$parentNodesScope,y.siblings(),y.index()+1),g=!1)));P&&m.parent()[0]!=P.$element[0]&&(P.resetEmptyElement(),P.resetDropzoneElement(),P=null),D?(P=T,T.$nodesScope.accept(a,0)&&u.moveTo(T.$nodesScope,T.$nodesScope.childNodes(),0)):q?(P=T,T.$nodesScope.accept(a,T.$nodesScope.childNodes().length)&&u.moveTo(T.$nodesScope,T.$nodesScope.childNodes(),T.$nodesScope.childNodes().length)):T.dragEnabled()&&(angular.isDefined(a.expandTimeoutOn)&&a.expandTimeoutOn!==T.id&&(l.cancel(a.expandTimeout),delete a.expandTimeout,delete a.expandTimeoutOn,a.$callbacks.expandTimeoutCancel()),T.collapsed&&(a.expandOnHover===!0||angular.isNumber(a.expandOnHover)&&0===a.expandOnHover?(T.collapsed=!1,T.$treeScope.$callbacks.toggle(!1,T)):a.expandOnHover!==!1&&angular.isNumber(a.expandOnHover)&&a.expandOnHover>0&&angular.isUndefined(a.expandTimeoutOn)&&(a.expandTimeoutOn=T.$id,a.$callbacks.expandTimeoutStart(),a.expandTimeout=l(function(){a.$callbacks.expandTimeoutEnd(),T.collapsed=!1,T.$treeScope.$callbacks.toggle(!1,T)},a.expandOnHover))),w=T.$element,Y=n.offset(w),I=n.height(w),L=T.$childNodesScope?T.$childNodesScope.$element:null,W=L?n.height(L):0,I-=W,k=M.appendChildOnHover?.25*I:n.height(w)/2,A=F.pageY0?D.exec(function(){x(e)},a.dragDelay):x(e)}),d.bind("touchend touchcancel mouseup",function(){a.dragDelay>0&&D.cancel()})},H(),O=function(){angular.element(o).bind("touchend",T),angular.element(o).bind("touchcancel",T),angular.element(o).bind("touchmove",C),angular.element(o).bind("mouseup",T),angular.element(o).bind("mousemove",C),angular.element(o).bind("mouseleave",w),angular.element(o).bind("keydown",A)},Y=function(){angular.element(o).unbind("touchend",T),angular.element(o).unbind("touchcancel",T),angular.element(o).unbind("touchmove",C),angular.element(o).unbind("mouseup",T),angular.element(o).unbind("mousemove",C),angular.element(o).unbind("mouseleave",w),angular.element(o).unbind("keydown",A)}}}}])}(),function(){"use strict";angular.module("ui.tree").directive("uiTreeNodes",["treeConfig","$window",function(e){return{require:["ngModel","?^uiTreeNode","^uiTree"],restrict:"A",scope:!0,controller:"TreeNodesController",link:function(n,t,o,l){var r={},a=l[0],d=l[1],i=l[2];angular.extend(r,e),r.nodesClass&&t.addClass(r.nodesClass),d?(d.scope.$childNodesScope=n,n.$nodeScope=d.scope):i.scope.$nodesScope=n,n.$treeScope=i.scope,a&&(a.$render=function(){n.$modelValue=a.$modelValue}),n.$watch(function(){return o.maxDepth},function(e){"number"==typeof e&&(n.maxDepth=e)}),n.$watch(function(){return o.nodropEnabled},function(e){"undefined"!=typeof e&&(n.nodropEnabled=!0)},!0)}}}])}(),function(){"use strict";function e(e,n){if(void 0===n)return null;for(var t=n.parentNode,o=1,l="function"==typeof t.setAttribute&&t.hasAttribute(e)?t:null;t&&"function"==typeof t.setAttribute&&!t.hasAttribute(e);){if(t=t.parentNode,l=t,t===document.documentElement){l=null;break}o++}return l}angular.module("ui.tree").factory("UiTreeHelper",["$document","$window","treeConfig",function(n,t,o){return{nodesData:{},setNodeAttribute:function(e,n,t){if(!e.$modelValue)return null;var o=this.nodesData[e.$modelValue.$$hashKey];o||(o={},this.nodesData[e.$modelValue.$$hashKey]=o),o[n]=t},getNodeAttribute:function(e,n){if(!e.$modelValue)return null;var t=this.nodesData[e.$modelValue.$$hashKey];return t?t[n]:null},nodrag:function(e){return"undefined"!=typeof e.attr("data-nodrag")&&"false"!==e.attr("data-nodrag")},eventObj:function(e){var n=e;return void 0!==e.targetTouches?n=e.targetTouches.item(0):void 0!==e.originalEvent&&void 0!==e.originalEvent.targetTouches&&(n=e.originalEvent.targetTouches.item(0)),n},dragInfo:function(e){return{source:e,sourceInfo:{cloneModel:e.$treeScope.cloneEnabled===!0?angular.copy(e.$modelValue):void 0,nodeScope:e,index:e.index(),nodesScope:e.$parentNodesScope},index:e.index(),siblings:e.siblings().slice(0),parent:e.$parentNodesScope,resetParent:function(){this.parent=e.$parentNodesScope},moveTo:function(e,n,t){this.parent=e,this.siblings=n.slice(0);var o=this.siblings.indexOf(this.source);o>-1&&(this.siblings.splice(o,1),this.source.index()0?this.siblings[this.index-1]:null},next:function(){return this.index0&&(o=e.originalEvent.touches[0].pageX,l=e.originalEvent.touches[0].pageY),t.offsetX=o-this.offset(n).left,t.offsetY=l-this.offset(n).top,t.startX=t.lastX=o,t.startY=t.lastY=l,t.nowX=t.nowY=t.distX=t.distY=t.dirAx=0,t.dirX=t.dirY=t.lastDirX=t.lastDirY=t.distAxX=t.distAxY=0,t},positionMoved:function(e,n,t){var o,l=e.pageX,r=e.pageY;return e.originalEvent&&e.originalEvent.touches&&e.originalEvent.touches.length>0&&(l=e.originalEvent.touches[0].pageX,r=e.originalEvent.touches[0].pageY),n.lastX=n.nowX,n.lastY=n.nowY,n.nowX=l,n.nowY=r,n.distX=n.nowX-n.lastX,n.distY=n.nowY-n.lastY,n.lastDirX=n.dirX,n.lastDirY=n.dirY,n.dirX=0===n.distX?0:n.distX>0?1:-1,n.dirY=0===n.distY?0:n.distY>0?1:-1,o=Math.abs(n.distX)>Math.abs(n.distY)?1:0,t?(n.dirAx=o,void(n.moving=!0)):(n.dirAx!==o?(n.distAxX=0,n.distAxY=0):(n.distAxX+=Math.abs(n.distX),0!==n.dirX&&n.dirX!==n.lastDirX&&(n.distAxX=0),n.distAxY+=Math.abs(n.distY),0!==n.dirY&&n.dirY!==n.lastDirY&&(n.distAxY=0)),void(n.dirAx=o))},elementIsTreeNode:function(e){return"undefined"!=typeof e.attr("ui-tree-node")},elementIsTreeNodeHandle:function(e){return"undefined"!=typeof e.attr("ui-tree-handle")},elementIsTree:function(e){return"undefined"!=typeof e.attr("ui-tree")},elementIsTreeNodes:function(e){return"undefined"!=typeof e.attr("ui-tree-nodes")},elementIsPlaceholder:function(e){return e.hasClass(o.placeholderClass)},elementIsDropzone:function(e){return e.hasClass(o.dropzoneClass)},elementContainsTreeNodeHandler:function(e){return e[0].querySelectorAll("[ui-tree-handle]").length>=1},treeNodeHandlerContainerOfElement:function(n){return e("ui-tree-handle",n[0])}}}])}(); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-underscore/angular-underscore.js b/src/main/resources/static/module/angular-underscore/angular-underscore.js new file mode 100644 index 0000000..55c9f41 --- /dev/null +++ b/src/main/resources/static/module/angular-underscore/angular-underscore.js @@ -0,0 +1,157 @@ +(function (ng, _) { + 'use strict'; + + var + underscoreModule = ng.module('angular-underscore', []), + utilsModule = ng.module('angular-underscore/utils', []), + filtersModule = ng.module('angular-underscore/filters', []); + + // begin custom _ + + function propGetterFactory(prop) { + return function(obj) {return obj[prop];}; + } + + _._ = _; + + // Shiv "min", "max" ,"sortedIndex" to accept property predicate. + _.each(['min', 'max', 'sortedIndex'], function(fnName) { + _[fnName] = _.wrap(_[fnName], function(fn) { + var args = _.toArray(arguments).slice(1); + + if(_.isString(args[2])) { + // for "sortedIndex", transmuting str to property getter + args[2] = propGetterFactory(args[2]); + } + else if(_.isString(args[1])) { + // for "min" or "max", transmuting str to property getter + args[1] = propGetterFactory(args[1]); + } + + return fn.apply(_, args); + }); + }); + + // Shiv "filter", "reject" to angular's built-in, + // and reserve underscore's feature(works on obj). + ng.injector(['ng']).invoke(['$filter', function($filter) { + _.filter = _.select = _.wrap($filter('filter'), function(filter, obj, exp, comparator) { + if(!(_.isArray(obj))) { + obj = _.toArray(obj); + } + + return filter(obj, exp, comparator); + }); + + _.reject = function(obj, exp) { + // use angular built-in negated predicate + if(_.isString(exp)) { + return _.filter(obj, '!' + exp); + } + + var diff = _.bind(_.difference, _, obj); + + return diff(_.filter(obj, exp)); + }; + }]); + + // end custom _ + + + // begin register angular-underscore/utils + + _.each(_.methods(_), function(methodName) { + function register($rootScope) {$rootScope[methodName] = _.bind(_[methodName], _);} + + _.each([ + underscoreModule, + utilsModule, + ng.module('angular-underscore/utils/' + methodName, []) + ], function(module) { + module.run(['$rootScope', register]); + }); + }); + + // end register angular-underscore/utils + + + // begin register angular-underscore/filters + + var + adapList = [ + ['map', 'collect'], + ['reduce', 'inject', 'foldl'], + ['reduceRight', 'foldr'], + ['find', 'detect'], + ['filter', 'select'], + 'where', + 'findWhere', + 'reject', + 'invoke', + 'pluck', + 'max', + 'min', + 'sortBy', + 'groupBy', + 'indexBy', + 'countBy', + 'shuffle', + 'sample', + 'toArray', + 'size', + ['first', 'head', 'take'], + 'initial', + 'last', + ['rest', 'tail', 'drop'], + 'compact', + 'flatten', + 'without', + 'partition', + 'union', + 'intersection', + 'difference', + ['uniq', 'unique'], + 'zip', + 'object', + 'indexOf', + 'lastIndexOf', + 'sortedIndex', + 'keys', + 'values', + 'pairs', + 'invert', + ['functions', 'methods'], + 'pick', + 'omit', + 'tap', + 'identity', + 'uniqueId', + 'escape', + 'unescape', + 'result', + 'template' + ]; + + _.each(adapList, function(filterNames) { + if(!(_.isArray(filterNames))) { + filterNames = [filterNames]; + } + + var + filter = _.bind(_[filterNames[0]], _), + filterFactory = function() {return filter;}; + + _.each(filterNames, function(filterName) { + _.each([ + underscoreModule, + filtersModule, + ng.module('angular-underscore/filters/' + filterName, []) + ], function(module) { + module.filter(filterName, filterFactory); + }); + }); + }); + + // end register angular-underscore/filters + +}(angular, _)); diff --git a/src/main/resources/static/module/angular-underscore/angular-underscore.min.js b/src/main/resources/static/module/angular-underscore/angular-underscore.min.js new file mode 100644 index 0000000..5a087b1 --- /dev/null +++ b/src/main/resources/static/module/angular-underscore/angular-underscore.min.js @@ -0,0 +1 @@ +(function(ng,_){"use strict";var underscoreModule=ng.module("angular-underscore",[]),utilsModule=ng.module("angular-underscore/utils",[]),filtersModule=ng.module("angular-underscore/filters",[]);function propGetterFactory(prop){return function(obj){return obj[prop]}}_._=_;_.each(["min","max","sortedIndex"],function(fnName){_[fnName]=_.wrap(_[fnName],function(fn){var args=_.toArray(arguments).slice(1);if(_.isString(args[2])){args[2]=propGetterFactory(args[2])}else if(_.isString(args[1])){args[1]=propGetterFactory(args[1])}return fn.apply(_,args)})});ng.injector(["ng"]).invoke(["$filter",function($filter){_.filter=_.select=_.wrap($filter("filter"),function(filter,obj,exp){if(!_.isArray(obj)){obj=_.toArray(obj)}return filter(obj,exp)});_.reject=function(obj,exp){if(_.isString(exp)){return _.filter(obj,"!"+exp)}var diff=_.bind(_.difference,_,obj);return diff(_.filter(obj,exp))}}]);_.each(_.methods(_),function(methodName){function register($rootScope){$rootScope[methodName]=_.bind(_[methodName],_)}_.each([underscoreModule,utilsModule,ng.module("angular-underscore/utils/"+methodName,[])],function(module){module.run(["$rootScope",register])})});var adapList=[["map","collect"],["reduce","inject","foldl"],["reduceRight","foldr"],["find","detect"],["filter","select"],"where","findWhere","reject","invoke","pluck","max","min","sortBy","groupBy","countBy","shuffle","toArray","size",["first","head","take"],"initial","last",["rest","tail","drop"],"compact","flatten","without","union","intersection","difference",["uniq","unique"],"zip","object","indexOf","lastIndexOf","sortedIndex","keys","values","pairs","invert",["functions","methods"],"pick","omit","tap","identity","uniqueId","escape","result","template"];_.each(adapList,function(filterNames){if(!_.isArray(filterNames)){filterNames=[filterNames]}var filter=_.bind(_[filterNames[0]],_),filterFactory=function(){return filter};_.each(filterNames,function(filterName){_.each([underscoreModule,filtersModule,ng.module("angular-underscore/filters/"+filterName,[])],function(module){module.filter(filterName,filterFactory)})})})})(angular,_); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-url-parser/angular-url-parser.js b/src/main/resources/static/module/angular-url-parser/angular-url-parser.js new file mode 100644 index 0000000..d115957 --- /dev/null +++ b/src/main/resources/static/module/angular-url-parser/angular-url-parser.js @@ -0,0 +1,213 @@ +/** + * Angular service to get simple methods to manipulate url parts + * + * @version 0.0.3 - 2017-06-22 + * @link https://github.com/yllieth/angular-url-parser + * @license MIT License, http://www.opensource.org/licenses/MIT + */ +angular + .module('ngUrlParser', []) + .factory('urlParser', function () { + 'use strict'; + + function urlParser(url) { + var parser = document.createElement('a'), searchObject = {}, queries, split, i; + + // Let the browser do the work + parser.href = url; + + // Convert query string to object + queries = parser.search.replace(/^\?/, '').split('&'); + + for( i = 0; i < queries.length; i++ ) { + split = queries[i].split('='); + // handle query strings such as id=1&id=2&id=3 + if(searchObject.hasOwnProperty(split[0])) { + var currentVal = searchObject[split[0]]; + var valueList; + if(!angular.isArray(currentVal)){ + valueList = []; + valueList.push(currentVal); + } else { + valueList = currentVal; + } + valueList.push(split[1]); + searchObject[split[0]] = valueList; + } else { + searchObject[split[0]] = split[1]; + } + } + + return { + protocol: parser.protocol, // ex: http: + host: parser.host, // ex: localhost:3000 + hostname: parser.hostname, // ex: localhost + port: parser.port, // ex: 3000 + pathname: parser.pathname, // ex: /models + search: parser.search, + searchObject: searchObject, + hash: parser.hash + }; + } + + return { + /** + * Returns an object with url parts placed in different properties + * + * @param {string} [url] - location.href if not specified + * @returns {{protocol, host, hostname, port, pathname, search, searchObject, hash}} + */ + parse: function (url) { + url = url || window.location.href; + return urlParser(url); + }, + + /** + * Returns the protocol part of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc' + * > Output: 'http:' + * + * @param {string} [url] - location.href if not specified + * @returns {string} + */ + getProtocol: function (url) { + url = url || window.location.href; + return this.parse(url).protocol; + }, + + /** + * Returns the host part of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc' + * > Output: 'localhost:3000' + * + * @param {string} [url] - location.href if not specified + * @returns {string} + */ + getHost: function (url) { + url = url || window.location.href; + return this.parse(url).host; + }, + + /** + * Returns the hostname part of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc' + * > Output: 'localhost' + * + * @param {string} [url] - location.href if not specified + * @returns {string} + */ + getHostname: function (url) { + url = url || window.location.href; + return this.parse(url).hostname; + }, + + /** + * Returns the port of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc' + * > Output: '3000' + * + * @param {string} [url] - location.href if not specified + * @returns {string} + */ + getPort: function (url) { + url = url || window.location.href; + return this.parse(url).port; + }, + + /** + * Returns the pathname part of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc' + * > Output: '/models' + * + * @param {string} [url] - location.href if not specified + * @returns {string} + */ + getRoute: function (url) { + url = url || window.location.href; + return this.parse(url).pathname; + }, + + /** + * Returns the list of element in the pathname part of the given url + * + * Example: + * > Input: 'http://localhost:3000/models/047256ce-850c-4408-83eb-4da873690b1c?sort=asc' + * > Output: ['models', '047256ce-850c-4408-83eb-4da873690b1c'] + * + * @param {string} [url] - location.href if not specified + * @returns {Array} + */ + getRouteAttributes: function(url) { + return this.getRoute(url).split('/'); + }, + + /** + * Returns the query part of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc' + * > Output: '?sort=asc' + * + * @param {string} [url] - location.href if not specified + * @returns {string} + */ + getQuerystring: function (url) { + url = url || window.location.href; + return this.parse(url).search; + }, + + /** + * Returns a single option or the whole query string of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc' + * > Output: {sort: 'asc'} + * + * > Input: 'http://localhost:3000/models?sort=asc' - sort + * > Output: 'asc' + * + * @param {string} [param] - + * @param {string} [url] - location.href if not specified + * @returns {object} if param is not defined + * @returns {string} if param is a valid parameter of the given url + */ + getOption: function (param, url) { + url = url || window.location.href; + + var searchOject = this.parse(url).searchObject; + + if (typeof param === 'string') { + return (searchOject.hasOwnProperty(param) === true) + ? searchOject[param] + : null; + } else { + return searchOject; + } + }, + + /** + * Returns the hash part of the given url + * + * Example: + * > Input: 'http://localhost:3000/models?sort=asc#quantiles' + * > Output: 'quantiles' + * + * @param {string} [url] - location.href if not specified + * @returns {string} + */ + getHash: function (url) { + url = url || window.location.href; + return this.parse(url).hash; + } + }; + }); diff --git a/src/main/resources/static/module/angular-url-parser/angular-url-parser.min.js b/src/main/resources/static/module/angular-url-parser/angular-url-parser.min.js new file mode 100644 index 0000000..c5167a3 --- /dev/null +++ b/src/main/resources/static/module/angular-url-parser/angular-url-parser.min.js @@ -0,0 +1 @@ +angular.module("ngUrlParser",[]).factory("urlParser",function(){"use strict";function t(t){var r,e,o,n=document.createElement("a"),a={};for(n.href=t,r=n.search.replace(/^\?/,"").split("&"),o=0;o 0; i >>>= 1, z += z) { + if (i & 1) { + string = z + string; + } + } + return string; + }; + + var fromParts = function(timeLow, timeMid, timeHiAndVersion, clockSeqHiAndReserved, clockSeqLow, node) { + var hex = paddedString(timeLow.toString(16), 8) + + '-' + + paddedString(timeMid.toString(16), 4) + + '-' + + paddedString(timeHiAndVersion.toString(16), 4) + + '-' + + paddedString(clockSeqHiAndReserved.toString(16), 2) + + paddedString(clockSeqLow.toString(16), 2) + + '-' + + paddedString(node.toString(16), 12); + return hex; + }; + + return { + generate: function () { + return fromParts( + randomUI32(), + randomUI16(), + 0x4000 | randomUI12(), + 0x80 | randomUI06(), + randomUI08(), + randomUI48() + ); + }, + + // addition by Ka-Jan to test for validity + // Based on: http://stackoverflow.com/questions/7905929/how-to-test-valid-uuid-guid + validate: function (uuid) { + var testPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + return testPattern.test(uuid); + } + }; + }); + +}(angular)); diff --git a/src/main/resources/static/module/angular-websocket/angular-websocket-mock.js b/src/main/resources/static/module/angular-websocket/angular-websocket-mock.js new file mode 100644 index 0000000..21bb08a --- /dev/null +++ b/src/main/resources/static/module/angular-websocket/angular-websocket-mock.js @@ -0,0 +1,139 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(['module', 'angular'], factory); + } else if (typeof exports !== "undefined") { + factory(module, require('angular')); + } else { + var mod = { + exports: {} + }; + factory(mod, global.angular); + global.angularWebsocketMock = mod.exports; + } +})(this, function (module, _angular) { + 'use strict'; + + var _angular2 = _interopRequireDefault(_angular); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + function $WebSocketBackend() { + var connectQueue = []; + var pendingConnects = []; + var closeQueue = []; + var pendingCloses = []; + var sendQueue = []; + var pendingSends = []; + var mock = false; + + function $MockWebSocket(url, protocols) { + this.protocols = protocols; + this.ssl = /(wss)/i.test(this.url); + } + + $MockWebSocket.prototype.send = function (msg) { + pendingSends.push(msg); + }; + + this.mockSend = function () { + if (mock) { + return sendQueue.shift(); + } + }; + + this.mock = function () { + mock = true; + }; + + this.isMocked = function () { + return mock; + }; + + this.isConnected = function (url) { + return connectQueue.indexOf(url) > -1; + }; + + $MockWebSocket.prototype.close = function () { + pendingCloses.push(true); + }; + + function createWebSocketBackend(url, protocols) { + pendingConnects.push(url); + // pendingConnects.push({ + // url: url, + // protocols: protocols + // }); + + if (protocols) { + return new $MockWebSocket(url, protocols); + } + return new $MockWebSocket(url); + } + this.create = createWebSocketBackend; + this.createWebSocketBackend = createWebSocketBackend; + + this.flush = function () { + var url, msg, config; + while (url = pendingConnects.shift()) { + var i = connectQueue.indexOf(url); + if (i > -1) { + connectQueue.splice(i, 1); + } + // if (config && config.url) { + // } + } + + while (pendingCloses.shift()) { + closeQueue.shift(); + } + + while (msg = pendingSends.shift()) { + var j; + sendQueue.forEach(function (pending, i) { + if (pending.message === msg.message) { + j = i; + } + }); + + if (j > -1) { + sendQueue.splice(j, 1); + } + } + }; + + this.expectConnect = function (url, protocols) { + connectQueue.push(url); + // connectQueue.push({url: url, protocols: protocols}); + }; + + this.expectClose = function () { + closeQueue.push(true); + }; + + this.expectSend = function (msg) { + sendQueue.push(msg); + }; + + this.verifyNoOutstandingExpectation = function () { + if (connectQueue.length || closeQueue.length || sendQueue.length) { + throw new Error('Requests waiting to be flushed'); + } + }; + + this.verifyNoOutstandingRequest = function () { + if (pendingConnects.length || pendingCloses.length || pendingSends.length) { + throw new Error('Requests waiting to be processed'); + } + }; + } // end $WebSocketBackend + + _angular2.default.module('ngWebSocketMock', []).service('WebSocketBackend', $WebSocketBackend).service('$websocketBackend', $WebSocketBackend); + + _angular2.default.module('angular-websocket-mock', ['ngWebSocketMock']); + + module.exports = _angular2.default.module('ngWebSocketMock'); +}); \ No newline at end of file diff --git a/src/main/resources/static/module/angular-websocket/angular-websocket.js b/src/main/resources/static/module/angular-websocket/angular-websocket.js new file mode 100644 index 0000000..db99c8e --- /dev/null +++ b/src/main/resources/static/module/angular-websocket/angular-websocket.js @@ -0,0 +1,415 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(['module', 'exports', 'angular', 'ws'], factory); + } else if (typeof exports !== "undefined") { + factory(module, exports, require('angular'), require('ws')); + } else { + var mod = { + exports: {} + }; + factory(mod, mod.exports, global.angular, global.ws); + global.angularWebsocket = mod.exports; + } +})(this, function (module, exports, _angular, ws) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _angular2 = _interopRequireDefault(_angular); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + var Socket; + + if (typeof window === 'undefined') { + try { + + Socket = ws.Client || ws.client || ws; + } catch (e) {} + } + + // Browser + Socket = Socket || window.WebSocket || window.MozWebSocket; + + var noop = _angular2.default.noop; + var objectFreeze = Object.freeze ? Object.freeze : noop; + var objectDefineProperty = Object.defineProperty; + var isString = _angular2.default.isString; + var isFunction = _angular2.default.isFunction; + var isDefined = _angular2.default.isDefined; + var isObject = _angular2.default.isObject; + var isArray = _angular2.default.isArray; + var forEach = _angular2.default.forEach; + var arraySlice = Array.prototype.slice; + // ie8 wat + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function (elt /*, from*/) { + var len = this.length >>> 0; + var from = Number(arguments[1]) || 0; + from = from < 0 ? Math.ceil(from) : Math.floor(from); + if (from < 0) { + from += len; + } + + for (; from < len; from++) { + if (from in this && this[from] === elt) { + return from; + } + } + return -1; + }; + } + + // $WebSocketProvider.$inject = ['$rootScope', '$q', '$timeout', '$websocketBackend']; + function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { + + function $WebSocket(url, protocols, options) { + if (!options && isObject(protocols) && !isArray(protocols)) { + options = protocols; + protocols = undefined; + } + + this.protocols = protocols; + this.url = url || 'Missing URL'; + this.ssl = /(wss)/i.test(this.url); + + // this.binaryType = ''; + // this.extensions = ''; + // this.bufferedAmount = 0; + // this.trasnmitting = false; + // this.buffer = []; + + // TODO: refactor options to use isDefined + this.scope = options && options.scope || $rootScope; + this.rootScopeFailover = options && options.rootScopeFailover && true; + this.useApplyAsync = options && options.useApplyAsync || false; + this.initialTimeout = options && options.initialTimeout || 500; // 500ms + this.maxTimeout = options && options.maxTimeout || 5 * 60 * 1000; // 5 minutes + this.reconnectIfNotNormalClose = options && options.reconnectIfNotNormalClose || false; + this.binaryType = options && options.binaryType || 'blob'; + + this._reconnectAttempts = 0; + this.sendQueue = []; + this.onOpenCallbacks = []; + this.onMessageCallbacks = []; + this.onErrorCallbacks = []; + this.onCloseCallbacks = []; + + objectFreeze(this._readyStateConstants); + + if (url) { + this._connect(); + } else { + this._setInternalState(0); + } + } + + $WebSocket.prototype._readyStateConstants = { + 'CONNECTING': 0, + 'OPEN': 1, + 'CLOSING': 2, + 'CLOSED': 3, + 'RECONNECT_ABORTED': 4 + }; + + $WebSocket.prototype._normalCloseCode = 1000; + + $WebSocket.prototype._reconnectableStatusCodes = [4000]; + + $WebSocket.prototype.safeDigest = function safeDigest(autoApply) { + if (autoApply && !this.scope.$$phase) { + this.scope.$digest(); + } + }; + + $WebSocket.prototype.bindToScope = function bindToScope(scope) { + var self = this; + if (scope) { + this.scope = scope; + if (this.rootScopeFailover) { + this.scope.$on('$destroy', function () { + self.scope = $rootScope; + }); + } + } + return self; + }; + + $WebSocket.prototype._connect = function _connect(force) { + if (force || !this.socket || this.socket.readyState !== this._readyStateConstants.OPEN) { + this.socket = $websocketBackend.create(this.url, this.protocols); + this.socket.onmessage = _angular2.default.bind(this, this._onMessageHandler); + this.socket.onopen = _angular2.default.bind(this, this._onOpenHandler); + this.socket.onerror = _angular2.default.bind(this, this._onErrorHandler); + this.socket.onclose = _angular2.default.bind(this, this._onCloseHandler); + this.socket.binaryType = this.binaryType; + } + }; + + $WebSocket.prototype.fireQueue = function fireQueue() { + while (this.sendQueue.length && this.socket.readyState === this._readyStateConstants.OPEN) { + var data = this.sendQueue.shift(); + + this.socket.send(isString(data.message) || this.binaryType != 'blob' ? data.message : JSON.stringify(data.message)); + data.deferred.resolve(); + } + }; + + $WebSocket.prototype.notifyOpenCallbacks = function notifyOpenCallbacks(event) { + for (var i = 0; i < this.onOpenCallbacks.length; i++) { + this.onOpenCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.notifyCloseCallbacks = function notifyCloseCallbacks(event) { + for (var i = 0; i < this.onCloseCallbacks.length; i++) { + this.onCloseCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.notifyErrorCallbacks = function notifyErrorCallbacks(event) { + for (var i = 0; i < this.onErrorCallbacks.length; i++) { + this.onErrorCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.onOpen = function onOpen(cb) { + this.onOpenCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onClose = function onClose(cb) { + this.onCloseCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onError = function onError(cb) { + this.onErrorCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onMessage = function onMessage(callback, options) { + if (!isFunction(callback)) { + throw new Error('Callback must be a function'); + } + + if (options && isDefined(options.filter) && !isString(options.filter) && !(options.filter instanceof RegExp)) { + throw new Error('Pattern must be a string or regular expression'); + } + + this.onMessageCallbacks.push({ + fn: callback, + pattern: options ? options.filter : undefined, + autoApply: options ? options.autoApply : true + }); + return this; + }; + + $WebSocket.prototype._onOpenHandler = function _onOpenHandler(event) { + this._reconnectAttempts = 0; + this.notifyOpenCallbacks(event); + this.fireQueue(); + }; + + $WebSocket.prototype._onCloseHandler = function _onCloseHandler(event) { + var self = this; + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + self.notifyCloseCallbacks(event); + }); + } else { + self.notifyCloseCallbacks(event); + self.safeDigest(true); + } + if (this.reconnectIfNotNormalClose && event.code !== this._normalCloseCode || this._reconnectableStatusCodes.indexOf(event.code) > -1) { + this.reconnect(); + } + }; + + $WebSocket.prototype._onErrorHandler = function _onErrorHandler(event) { + var self = this; + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + self.notifyErrorCallbacks(event); + }); + } else { + self.notifyErrorCallbacks(event); + self.safeDigest(true); + } + }; + + $WebSocket.prototype._onMessageHandler = function _onMessageHandler(message) { + var pattern; + var self = this; + var currentCallback; + for (var i = 0; i < self.onMessageCallbacks.length; i++) { + currentCallback = self.onMessageCallbacks[i]; + pattern = currentCallback.pattern; + if (pattern) { + if (isString(pattern) && message.data === pattern) { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } else if (pattern instanceof RegExp && pattern.exec(message.data)) { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } + } else { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } + } + + function applyAsyncOrDigest(callback, autoApply, args) { + args = arraySlice.call(arguments, 2); + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + callback.apply(self, args); + }); + } else { + callback.apply(self, args); + self.safeDigest(autoApply); + } + } + }; + + $WebSocket.prototype.close = function close(force) { + if (force || !this.socket.bufferedAmount) { + this.socket.close(); + } + return this; + }; + + $WebSocket.prototype.send = function send(data) { + var deferred = $q.defer(); + var self = this; + var promise = cancelableify(deferred.promise); + + if (self.readyState === self._readyStateConstants.RECONNECT_ABORTED) { + deferred.reject('Socket connection has been closed'); + } else { + self.sendQueue.push({ + message: data, + deferred: deferred + }); + self.fireQueue(); + } + + // Credit goes to @btford + function cancelableify(promise) { + promise.cancel = cancel; + var then = promise.then; + promise.then = function () { + var newPromise = then.apply(this, arguments); + return cancelableify(newPromise); + }; + return promise; + } + + function cancel(reason) { + self.sendQueue.splice(self.sendQueue.indexOf(data), 1); + deferred.reject(reason); + return self; + } + + if ($websocketBackend.isMocked && $websocketBackend.isMocked() && $websocketBackend.isConnected(this.url)) { + this._onMessageHandler($websocketBackend.mockSend()); + } + + return promise; + }; + + $WebSocket.prototype.reconnect = function reconnect() { + this.close(); + + var backoffDelay = this._getBackoffDelay(++this._reconnectAttempts); + + var backoffDelaySeconds = backoffDelay / 1000; + console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); + + $timeout(_angular2.default.bind(this, this._connect), backoffDelay); + + return this; + }; + // Exponential Backoff Formula by Prof. Douglas Thain + // http://dthain.blogspot.co.uk/2009/02/exponential-backoff-in-distributed.html + $WebSocket.prototype._getBackoffDelay = function _getBackoffDelay(attempt) { + var R = Math.random() + 1; + var T = this.initialTimeout; + var F = 2; + var N = attempt; + var M = this.maxTimeout; + + return Math.floor(Math.min(R * T * Math.pow(F, N), M)); + }; + + $WebSocket.prototype._setInternalState = function _setInternalState(state) { + if (Math.floor(state) !== state || state < 0 || state > 4) { + throw new Error('state must be an integer between 0 and 4, got: ' + state); + } + + // ie8 wat + if (!objectDefineProperty) { + this.readyState = state || this.socket.readyState; + } + this._internalConnectionState = state; + + forEach(this.sendQueue, function (pending) { + pending.deferred.reject('Message cancelled due to closed socket connection'); + }); + }; + + // Read only .readyState + if (objectDefineProperty) { + objectDefineProperty($WebSocket.prototype, 'readyState', { + get: function get() { + return this._internalConnectionState || this.socket.readyState; + }, + set: function set() { + throw new Error('The readyState property is read-only'); + } + }); + } + + return function (url, protocols, options) { + return new $WebSocket(url, protocols, options); + }; + } + + // $WebSocketBackendProvider.$inject = ['$log']; + function $WebSocketBackendProvider($log) { + this.create = function create(url, protocols) { + var match = /wss?:\/\//.exec(url); + + if (!match) { + throw new Error('Invalid url provided'); + } + + if (protocols) { + return new Socket(url, protocols); + } + + return new Socket(url); + }; + + this.createWebSocketBackend = function createWebSocketBackend(url, protocols) { + $log.warn('Deprecated: Please use .create(url, protocols)'); + return this.create(url, protocols); + }; + } + + _angular2.default.module('ngWebSocket', []).factory('$websocket', ['$rootScope', '$q', '$timeout', '$websocketBackend', $WebSocketProvider]).factory('WebSocket', ['$rootScope', '$q', '$timeout', 'WebsocketBackend', $WebSocketProvider]).service('$websocketBackend', ['$log', $WebSocketBackendProvider]).service('WebSocketBackend', ['$log', $WebSocketBackendProvider]); + + _angular2.default.module('angular-websocket', ['ngWebSocket']); + + exports.default = _angular2.default.module('ngWebSocket'); + module.exports = exports['default']; +}); diff --git a/src/main/resources/static/module/angular-websocket/angular-websocket.min.js b/src/main/resources/static/module/angular-websocket/angular-websocket.min.js new file mode 100644 index 0000000..0d82580 --- /dev/null +++ b/src/main/resources/static/module/angular-websocket/angular-websocket.min.js @@ -0,0 +1,2 @@ +!function(e,t){if("function"==typeof define&&define.amd)define(["module","exports","angular","ws"],t);else if("undefined"!=typeof exports)t(module,exports,require("angular"),require("ws"));else{var o={exports:{}};t(o,o.exports,e.angular,e.ws),e.angularWebsocket=o.exports}}(this,function(e,t,o,n){"use strict";function s(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,o,n){function s(t,o,n){n||!k(o)||C(o)||(n=o,o=void 0),this.protocols=o,this.url=t||"Missing URL",this.ssl=/(wss)/i.test(this.url),this.scope=n&&n.scope||e,this.rootScopeFailover=n&&n.rootScopeFailover&&!0,this.useApplyAsync=n&&n.useApplyAsync||!1,this.initialTimeout=n&&n.initialTimeout||500,this.maxTimeout=n&&n.maxTimeout||3e5,this.reconnectIfNotNormalClose=n&&n.reconnectIfNotNormalClose||!1,this.binaryType=n&&n.binaryType||"blob",this._reconnectAttempts=0,this.sendQueue=[],this.onOpenCallbacks=[],this.onMessageCallbacks=[],this.onErrorCallbacks=[],this.onCloseCallbacks=[],f(this._readyStateConstants),t?this._connect():this._setInternalState(0)}return s.prototype._readyStateConstants={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3,RECONNECT_ABORTED:4},s.prototype._normalCloseCode=1e3,s.prototype._reconnectableStatusCodes=[4e3],s.prototype.safeDigest=function(e){e&&!this.scope.$$phase&&this.scope.$digest()},s.prototype.bindToScope=function(t){var o=this;return t&&(this.scope=t,this.rootScopeFailover&&this.scope.$on("$destroy",function(){o.scope=e})),o},s.prototype._connect=function(e){!e&&this.socket&&this.socket.readyState===this._readyStateConstants.OPEN||(this.socket=n.create(this.url,this.protocols),this.socket.onmessage=c["default"].bind(this,this._onMessageHandler),this.socket.onopen=c["default"].bind(this,this._onOpenHandler),this.socket.onerror=c["default"].bind(this,this._onErrorHandler),this.socket.onclose=c["default"].bind(this,this._onCloseHandler),this.socket.binaryType=this.binaryType)},s.prototype.fireQueue=function(){for(;this.sendQueue.length&&this.socket.readyState===this._readyStateConstants.OPEN;){var e=this.sendQueue.shift();this.socket.send(d(e.message)||"blob"!=this.binaryType?e.message:JSON.stringify(e.message)),e.deferred.resolve()}},s.prototype.notifyOpenCallbacks=function(e){for(var t=0;t-1)&&this.reconnect()},s.prototype._onErrorHandler=function(e){var t=this;t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyErrorCallbacks(e)}):(t.notifyErrorCallbacks(e),t.safeDigest(!0))},s.prototype._onMessageHandler=function(e){function t(e,t,o){o=m.call(arguments,2),s.useApplyAsync?s.scope.$applyAsync(function(){e.apply(s,o)}):(e.apply(s,o),s.safeDigest(t))}for(var o,n,s=this,r=0;re||e>4)throw new Error("state must be an integer between 0 and 4, got: "+e);h||(this.readyState=e||this.socket.readyState),this._internalConnectionState=e,g(this.sendQueue,function(e){e.deferred.reject("Message cancelled due to closed socket connection")})},h&&h(s.prototype,"readyState",{get:function(){return this._internalConnectionState||this.socket.readyState},set:function(){throw new Error("The readyState property is read-only")}}),function(e,t,o){return new s(e,t,o)}}function i(e){this.create=function(e,t){var o=/wss?:\/\//.exec(e);if(!o)throw new Error("Invalid url provided");return t?new a(e,t):new a(e)},this.createWebSocketBackend=function(t,o){return e.warn("Deprecated: Please use .create(url, protocols)"),this.create(t,o)}}Object.defineProperty(t,"__esModule",{value:!0});var a,c=s(o),l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};if("object"===("undefined"==typeof t?"undefined":l(t))&&"function"==typeof require)try{a=n.Client||n.client||n}catch(u){}a=a||window.WebSocket||window.MozWebSocket;var p=c["default"].noop,f=Object.freeze?Object.freeze:p,h=Object.defineProperty,d=c["default"].isString,y=c["default"].isFunction,b=c["default"].isDefined,k=c["default"].isObject,C=c["default"].isArray,g=c["default"].forEach,m=Array.prototype.slice;Array.prototype.indexOf||(Array.prototype.indexOf=function(e){var t=this.length>>>0,o=Number(arguments[1])||0;for(o=0>o?Math.ceil(o):Math.floor(o),0>o&&(o+=t);t>o;o++)if(o in this&&this[o]===e)return o;return-1}),c["default"].module("ngWebSocket",[]).factory("$websocket",["$rootScope","$q","$timeout","$websocketBackend",r]).factory("WebSocket",["$rootScope","$q","$timeout","WebsocketBackend",r]).service("$websocketBackend",["$log",i]).service("WebSocketBackend",["$log",i]),c["default"].module("angular-websocket",["ngWebSocket"]),t["default"]=c["default"].module("ngWebSocket"),e.exports=t["default"]}); +//# sourceMappingURL=angular-websocket.min.js.map diff --git a/src/main/resources/static/module/angular-websocket/angular-websocket.min.js.map b/src/main/resources/static/module/angular-websocket/angular-websocket.min.js.map new file mode 100644 index 0000000..0983906 --- /dev/null +++ b/src/main/resources/static/module/angular-websocket/angular-websocket.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["dist/angular-websocket.js"],"names":["global","factory","define","amd","exports","module","require","mod","angular","ws","angularWebsocket","this","_angular","_interopRequireDefault","obj","__esModule","default","$WebSocketProvider","$rootScope","$q","$timeout","$websocketBackend","$WebSocket","url","protocols","options","isObject","isArray","undefined","ssl","test","scope","rootScopeFailover","useApplyAsync","initialTimeout","maxTimeout","reconnectIfNotNormalClose","binaryType","_reconnectAttempts","sendQueue","onOpenCallbacks","onMessageCallbacks","onErrorCallbacks","onCloseCallbacks","objectFreeze","_readyStateConstants","_connect","_setInternalState","prototype","CONNECTING","OPEN","CLOSING","CLOSED","RECONNECT_ABORTED","_normalCloseCode","_reconnectableStatusCodes","safeDigest","autoApply","$$phase","$digest","bindToScope","self","$on","force","socket","readyState","create","onmessage","_angular2","bind","_onMessageHandler","onopen","_onOpenHandler","onerror","_onErrorHandler","onclose","_onCloseHandler","fireQueue","length","data","shift","send","isString","message","JSON","stringify","deferred","resolve","notifyOpenCallbacks","event","i","call","notifyCloseCallbacks","notifyErrorCallbacks","onOpen","cb","push","onClose","onError","onMessage","callback","isFunction","Error","isDefined","filter","RegExp","fn","pattern","$applyAsync","code","indexOf","reconnect","applyAsyncOrDigest","args","arraySlice","arguments","apply","currentCallback","exec","close","bufferedAmount","cancelableify","promise","cancel","then","newPromise","reason","splice","reject","defer","isMocked","isConnected","mockSend","backoffDelay","_getBackoffDelay","backoffDelaySeconds","console","log","attempt","R","Math","random","T","F","N","M","floor","min","pow","state","objectDefineProperty","_internalConnectionState","forEach","pending","get","set","$WebSocketBackendProvider","$log","match","Socket","createWebSocketBackend","warn","Object","defineProperty","value","_typeof","Symbol","iterator","constructor","Client","client","e","window","WebSocket","MozWebSocket","noop","freeze","Array","slice","elt","len","from","Number","ceil","service"],"mappings":"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"} \ No newline at end of file diff --git a/src/main/resources/static/module/angular/angular-animate.js b/src/main/resources/static/module/angular/angular-animate.js new file mode 100644 index 0000000..b18b828 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-animate.js @@ -0,0 +1,4139 @@ +/** + * @license AngularJS v1.5.8 + * (c) 2010-2016 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular) {'use strict'; + +var ELEMENT_NODE = 1; +var COMMENT_NODE = 8; + +var ADD_CLASS_SUFFIX = '-add'; +var REMOVE_CLASS_SUFFIX = '-remove'; +var EVENT_CLASS_PREFIX = 'ng-'; +var ACTIVE_CLASS_SUFFIX = '-active'; +var PREPARE_CLASS_SUFFIX = '-prepare'; + +var NG_ANIMATE_CLASSNAME = 'ng-animate'; +var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren'; + +// Detect proper transitionend/animationend event names. +var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; + +// If unprefixed events are not supported but webkit-prefixed are, use the latter. +// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. +// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` +// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. +// Register both events in case `window.onanimationend` is not supported because of that, +// do the same for `transitionend` as Safari is likely to exhibit similar behavior. +// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit +// therefore there is no reason to test anymore for other vendor prefixes: +// http://caniuse.com/#search=transition +if ((window.ontransitionend === void 0) && (window.onwebkittransitionend !== void 0)) { + CSS_PREFIX = '-webkit-'; + TRANSITION_PROP = 'WebkitTransition'; + TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; +} else { + TRANSITION_PROP = 'transition'; + TRANSITIONEND_EVENT = 'transitionend'; +} + +if ((window.onanimationend === void 0) && (window.onwebkitanimationend !== void 0)) { + CSS_PREFIX = '-webkit-'; + ANIMATION_PROP = 'WebkitAnimation'; + ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; +} else { + ANIMATION_PROP = 'animation'; + ANIMATIONEND_EVENT = 'animationend'; +} + +var DURATION_KEY = 'Duration'; +var PROPERTY_KEY = 'Property'; +var DELAY_KEY = 'Delay'; +var TIMING_KEY = 'TimingFunction'; +var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; +var ANIMATION_PLAYSTATE_KEY = 'PlayState'; +var SAFE_FAST_FORWARD_DURATION_VALUE = 9999; + +var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY; +var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY; +var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY; +var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY; + +var ngMinErr = angular.$$minErr('ng'); +function assertArg(arg, name, reason) { + if (!arg) { + throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); + } + return arg; +} + +function mergeClasses(a,b) { + if (!a && !b) return ''; + if (!a) return b; + if (!b) return a; + if (isArray(a)) a = a.join(' '); + if (isArray(b)) b = b.join(' '); + return a + ' ' + b; +} + +function packageStyles(options) { + var styles = {}; + if (options && (options.to || options.from)) { + styles.to = options.to; + styles.from = options.from; + } + return styles; +} + +function pendClasses(classes, fix, isPrefix) { + var className = ''; + classes = isArray(classes) + ? classes + : classes && isString(classes) && classes.length + ? classes.split(/\s+/) + : []; + forEach(classes, function(klass, i) { + if (klass && klass.length > 0) { + className += (i > 0) ? ' ' : ''; + className += isPrefix ? fix + klass + : klass + fix; + } + }); + return className; +} + +function removeFromArray(arr, val) { + var index = arr.indexOf(val); + if (val >= 0) { + arr.splice(index, 1); + } +} + +function stripCommentsFromElement(element) { + if (element instanceof jqLite) { + switch (element.length) { + case 0: + return element; + + case 1: + // there is no point of stripping anything if the element + // is the only element within the jqLite wrapper. + // (it's important that we retain the element instance.) + if (element[0].nodeType === ELEMENT_NODE) { + return element; + } + break; + + default: + return jqLite(extractElementNode(element)); + } + } + + if (element.nodeType === ELEMENT_NODE) { + return jqLite(element); + } +} + +function extractElementNode(element) { + if (!element[0]) return element; + for (var i = 0; i < element.length; i++) { + var elm = element[i]; + if (elm.nodeType == ELEMENT_NODE) { + return elm; + } + } +} + +function $$addClass($$jqLite, element, className) { + forEach(element, function(elm) { + $$jqLite.addClass(elm, className); + }); +} + +function $$removeClass($$jqLite, element, className) { + forEach(element, function(elm) { + $$jqLite.removeClass(elm, className); + }); +} + +function applyAnimationClassesFactory($$jqLite) { + return function(element, options) { + if (options.addClass) { + $$addClass($$jqLite, element, options.addClass); + options.addClass = null; + } + if (options.removeClass) { + $$removeClass($$jqLite, element, options.removeClass); + options.removeClass = null; + } + }; +} + +function prepareAnimationOptions(options) { + options = options || {}; + if (!options.$$prepared) { + var domOperation = options.domOperation || noop; + options.domOperation = function() { + options.$$domOperationFired = true; + domOperation(); + domOperation = noop; + }; + options.$$prepared = true; + } + return options; +} + +function applyAnimationStyles(element, options) { + applyAnimationFromStyles(element, options); + applyAnimationToStyles(element, options); +} + +function applyAnimationFromStyles(element, options) { + if (options.from) { + element.css(options.from); + options.from = null; + } +} + +function applyAnimationToStyles(element, options) { + if (options.to) { + element.css(options.to); + options.to = null; + } +} + +function mergeAnimationDetails(element, oldAnimation, newAnimation) { + var target = oldAnimation.options || {}; + var newOptions = newAnimation.options || {}; + + var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || ''); + var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || ''); + var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove); + + if (newOptions.preparationClasses) { + target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses); + delete newOptions.preparationClasses; + } + + // noop is basically when there is no callback; otherwise something has been set + var realDomOperation = target.domOperation !== noop ? target.domOperation : null; + + extend(target, newOptions); + + // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this. + if (realDomOperation) { + target.domOperation = realDomOperation; + } + + if (classes.addClass) { + target.addClass = classes.addClass; + } else { + target.addClass = null; + } + + if (classes.removeClass) { + target.removeClass = classes.removeClass; + } else { + target.removeClass = null; + } + + oldAnimation.addClass = target.addClass; + oldAnimation.removeClass = target.removeClass; + + return target; +} + +function resolveElementClasses(existing, toAdd, toRemove) { + var ADD_CLASS = 1; + var REMOVE_CLASS = -1; + + var flags = {}; + existing = splitClassesToLookup(existing); + + toAdd = splitClassesToLookup(toAdd); + forEach(toAdd, function(value, key) { + flags[key] = ADD_CLASS; + }); + + toRemove = splitClassesToLookup(toRemove); + forEach(toRemove, function(value, key) { + flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS; + }); + + var classes = { + addClass: '', + removeClass: '' + }; + + forEach(flags, function(val, klass) { + var prop, allow; + if (val === ADD_CLASS) { + prop = 'addClass'; + allow = !existing[klass] || existing[klass + REMOVE_CLASS_SUFFIX]; + } else if (val === REMOVE_CLASS) { + prop = 'removeClass'; + allow = existing[klass] || existing[klass + ADD_CLASS_SUFFIX]; + } + if (allow) { + if (classes[prop].length) { + classes[prop] += ' '; + } + classes[prop] += klass; + } + }); + + function splitClassesToLookup(classes) { + if (isString(classes)) { + classes = classes.split(' '); + } + + var obj = {}; + forEach(classes, function(klass) { + // sometimes the split leaves empty string values + // incase extra spaces were applied to the options + if (klass.length) { + obj[klass] = true; + } + }); + return obj; + } + + return classes; +} + +function getDomNode(element) { + return (element instanceof jqLite) ? element[0] : element; +} + +function applyGeneratedPreparationClasses(element, event, options) { + var classes = ''; + if (event) { + classes = pendClasses(event, EVENT_CLASS_PREFIX, true); + } + if (options.addClass) { + classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX)); + } + if (options.removeClass) { + classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX)); + } + if (classes.length) { + options.preparationClasses = classes; + element.addClass(classes); + } +} + +function clearGeneratedClasses(element, options) { + if (options.preparationClasses) { + element.removeClass(options.preparationClasses); + options.preparationClasses = null; + } + if (options.activeClasses) { + element.removeClass(options.activeClasses); + options.activeClasses = null; + } +} + +function blockTransitions(node, duration) { + // we use a negative delay value since it performs blocking + // yet it doesn't kill any existing transitions running on the + // same element which makes this safe for class-based animations + var value = duration ? '-' + duration + 's' : ''; + applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]); + return [TRANSITION_DELAY_PROP, value]; +} + +function blockKeyframeAnimations(node, applyBlock) { + var value = applyBlock ? 'paused' : ''; + var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY; + applyInlineStyle(node, [key, value]); + return [key, value]; +} + +function applyInlineStyle(node, styleTuple) { + var prop = styleTuple[0]; + var value = styleTuple[1]; + node.style[prop] = value; +} + +function concatWithSpace(a,b) { + if (!a) return b; + if (!b) return a; + return a + ' ' + b; +} + +var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) { + var queue, cancelFn; + + function scheduler(tasks) { + // we make a copy since RAFScheduler mutates the state + // of the passed in array variable and this would be difficult + // to track down on the outside code + queue = queue.concat(tasks); + nextTick(); + } + + queue = scheduler.queue = []; + + /* waitUntilQuiet does two things: + * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through + * 2. It will delay the next wave of tasks from running until the quiet `fn` has run. + * + * The motivation here is that animation code can request more time from the scheduler + * before the next wave runs. This allows for certain DOM properties such as classes to + * be resolved in time for the next animation to run. + */ + scheduler.waitUntilQuiet = function(fn) { + if (cancelFn) cancelFn(); + + cancelFn = $$rAF(function() { + cancelFn = null; + fn(); + nextTick(); + }); + }; + + return scheduler; + + function nextTick() { + if (!queue.length) return; + + var items = queue.shift(); + for (var i = 0; i < items.length; i++) { + items[i](); + } + + if (!cancelFn) { + $$rAF(function() { + if (!cancelFn) nextTick(); + }); + } + } +}]; + +/** + * @ngdoc directive + * @name ngAnimateChildren + * @restrict AE + * @element ANY + * + * @description + * + * ngAnimateChildren allows you to specify that children of this element should animate even if any + * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move` + * (structural) animation, child elements that also have an active structural animation are not animated. + * + * Note that even if `ngAnimteChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation). + * + * + * @param {string} ngAnimateChildren If the value is empty, `true` or `on`, + * then child animations are allowed. If the value is `false`, child animations are not allowed. + * + * @example + * + +
    + + +
    +
    +
    + List of items: +
    Item {{item}}
    +
    +
    +
    +
    + + + .container.ng-enter, + .container.ng-leave { + transition: all ease 1.5s; + } + + .container.ng-enter, + .container.ng-leave-active { + opacity: 0; + } + + .container.ng-leave, + .container.ng-enter-active { + opacity: 1; + } + + .item { + background: firebrick; + color: #FFF; + margin-bottom: 10px; + } + + .item.ng-enter, + .item.ng-leave { + transition: transform 1.5s ease; + } + + .item.ng-enter { + transform: translateX(50px); + } + + .item.ng-enter-active { + transform: translateX(0); + } + + + angular.module('ngAnimateChildren', ['ngAnimate']) + .controller('mainController', function() { + this.animateChildren = false; + this.enterElement = false; + }); + +
    + */ +var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) { + return { + link: function(scope, element, attrs) { + var val = attrs.ngAnimateChildren; + if (isString(val) && val.length === 0) { //empty attribute + element.data(NG_ANIMATE_CHILDREN_DATA, true); + } else { + // Interpolate and set the value, so that it is available to + // animations that run right after compilation + setData($interpolate(val)(scope)); + attrs.$observe('ngAnimateChildren', setData); + } + + function setData(value) { + value = value === 'on' || value === 'true'; + element.data(NG_ANIMATE_CHILDREN_DATA, value); + } + } + }; +}]; + +var ANIMATE_TIMER_KEY = '$$animateCss'; + +/** + * @ngdoc service + * @name $animateCss + * @kind object + * + * @description + * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes + * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT + * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or + * directives to create more complex animations that can be purely driven using CSS code. + * + * Note that only browsers that support CSS transitions and/or keyframe animations are capable of + * rendering animations triggered via `$animateCss` (bad news for IE9 and lower). + * + * ## Usage + * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that + * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however, + * any automatic control over cancelling animations and/or preventing animations from being run on + * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to + * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger + * the CSS animation. + * + * The example below shows how we can create a folding animation on an element using `ng-if`: + * + * ```html + * + *
    + * This element will go BOOM + *
    + * + * ``` + * + * Now we create the **JavaScript animation** that will trigger the CSS transition: + * + * ```js + * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) { + * return { + * enter: function(element, doneFn) { + * var height = element[0].offsetHeight; + * return $animateCss(element, { + * from: { height:'0px' }, + * to: { height:height + 'px' }, + * duration: 1 // one second + * }); + * } + * } + * }]); + * ``` + * + * ## More Advanced Uses + * + * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks + * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code. + * + * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation, + * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with + * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order + * to provide a working animation that will run in CSS. + * + * The example below showcases a more advanced version of the `.fold-animation` from the example above: + * + * ```js + * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) { + * return { + * enter: function(element, doneFn) { + * var height = element[0].offsetHeight; + * return $animateCss(element, { + * addClass: 'red large-text pulse-twice', + * easing: 'ease-out', + * from: { height:'0px' }, + * to: { height:height + 'px' }, + * duration: 1 // one second + * }); + * } + * } + * }]); + * ``` + * + * Since we're adding/removing CSS classes then the CSS transition will also pick those up: + * + * ```css + * /* since a hardcoded duration value of 1 was provided in the JavaScript animation code, + * the CSS classes below will be transitioned despite them being defined as regular CSS classes */ + * .red { background:red; } + * .large-text { font-size:20px; } + * + * /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */ + * .pulse-twice { + * animation: 0.5s pulse linear 2; + * -webkit-animation: 0.5s pulse linear 2; + * } + * + * @keyframes pulse { + * from { transform: scale(0.5); } + * to { transform: scale(1.5); } + * } + * + * @-webkit-keyframes pulse { + * from { -webkit-transform: scale(0.5); } + * to { -webkit-transform: scale(1.5); } + * } + * ``` + * + * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen. + * + * ## How the Options are handled + * + * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation + * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline + * styles using the `from` and `to` properties. + * + * ```js + * var animator = $animateCss(element, { + * from: { background:'red' }, + * to: { background:'blue' } + * }); + * animator.start(); + * ``` + * + * ```css + * .rotating-animation { + * animation:0.5s rotate linear; + * -webkit-animation:0.5s rotate linear; + * } + * + * @keyframes rotate { + * from { transform: rotate(0deg); } + * to { transform: rotate(360deg); } + * } + * + * @-webkit-keyframes rotate { + * from { -webkit-transform: rotate(0deg); } + * to { -webkit-transform: rotate(360deg); } + * } + * ``` + * + * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is + * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition + * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition + * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied + * and spread across the transition and keyframe animation. + * + * ## What is returned + * + * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually + * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are + * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties: + * + * ```js + * var animator = $animateCss(element, { ... }); + * ``` + * + * Now what do the contents of our `animator` variable look like: + * + * ```js + * { + * // starts the animation + * start: Function, + * + * // ends (aborts) the animation + * end: Function + * } + * ``` + * + * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends. + * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and styles may have been + * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties + * and that changing them will not reconfigure the parameters of the animation. + * + * ### runner.done() vs runner.then() + * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the + * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**. + * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()` + * unless you really need a digest to kick off afterwards. + * + * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss + * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code). + * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works. + * + * @param {DOMElement} element the element that will be animated + * @param {object} options the animation-related options that will be applied during the animation + * + * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied + * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.) + * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and + * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted. + * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both). + * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`). + * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`). + * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation. + * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition. + * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation. + * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation. + * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0` + * is provided then the animation will be skipped entirely. + * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is + * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value + * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same + * CSS delay value. + * * `stagger` - A numeric time value representing the delay between successively animated elements + * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.}) + * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a + * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`) + * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occurring on the classes being added and removed.) + * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once + * the animation is closed. This is useful for when the styles are used purely for the sake of + * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation). + * By default this value is set to `false`. + * + * @return {object} an object with start and end methods and details about the animation. + * + * * `start` - The method to start the animation. This will return a `Promise` when called. + * * `end` - This method will cancel the animation and remove all applied CSS classes and styles. + */ +var ONE_SECOND = 1000; +var BASE_TEN = 10; + +var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; +var CLOSING_TIME_BUFFER = 1.5; + +var DETECT_CSS_PROPERTIES = { + transitionDuration: TRANSITION_DURATION_PROP, + transitionDelay: TRANSITION_DELAY_PROP, + transitionProperty: TRANSITION_PROP + PROPERTY_KEY, + animationDuration: ANIMATION_DURATION_PROP, + animationDelay: ANIMATION_DELAY_PROP, + animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY +}; + +var DETECT_STAGGER_CSS_PROPERTIES = { + transitionDuration: TRANSITION_DURATION_PROP, + transitionDelay: TRANSITION_DELAY_PROP, + animationDuration: ANIMATION_DURATION_PROP, + animationDelay: ANIMATION_DELAY_PROP +}; + +function getCssKeyframeDurationStyle(duration) { + return [ANIMATION_DURATION_PROP, duration + 's']; +} + +function getCssDelayStyle(delay, isKeyframeAnimation) { + var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP; + return [prop, delay + 's']; +} + +function computeCssStyles($window, element, properties) { + var styles = Object.create(null); + var detectedStyles = $window.getComputedStyle(element) || {}; + forEach(properties, function(formalStyleName, actualStyleName) { + var val = detectedStyles[formalStyleName]; + if (val) { + var c = val.charAt(0); + + // only numerical-based values have a negative sign or digit as the first value + if (c === '-' || c === '+' || c >= 0) { + val = parseMaxTime(val); + } + + // by setting this to null in the event that the delay is not set or is set directly as 0 + // then we can still allow for negative values to be used later on and not mistake this + // value for being greater than any other negative value. + if (val === 0) { + val = null; + } + styles[actualStyleName] = val; + } + }); + + return styles; +} + +function parseMaxTime(str) { + var maxValue = 0; + var values = str.split(/\s*,\s*/); + forEach(values, function(value) { + // it's always safe to consider only second values and omit `ms` values since + // getComputedStyle will always handle the conversion for us + if (value.charAt(value.length - 1) == 's') { + value = value.substring(0, value.length - 1); + } + value = parseFloat(value) || 0; + maxValue = maxValue ? Math.max(value, maxValue) : value; + }); + return maxValue; +} + +function truthyTimingValue(val) { + return val === 0 || val != null; +} + +function getCssTransitionDurationStyle(duration, applyOnlyDuration) { + var style = TRANSITION_PROP; + var value = duration + 's'; + if (applyOnlyDuration) { + style += DURATION_KEY; + } else { + value += ' linear all'; + } + return [style, value]; +} + +function createLocalCacheLookup() { + var cache = Object.create(null); + return { + flush: function() { + cache = Object.create(null); + }, + + count: function(key) { + var entry = cache[key]; + return entry ? entry.total : 0; + }, + + get: function(key) { + var entry = cache[key]; + return entry && entry.value; + }, + + put: function(key, value) { + if (!cache[key]) { + cache[key] = { total: 1, value: value }; + } else { + cache[key].total++; + } + } + }; +} + +// we do not reassign an already present style value since +// if we detect the style property value again we may be +// detecting styles that were added via the `from` styles. +// We make use of `isDefined` here since an empty string +// or null value (which is what getPropertyValue will return +// for a non-existing style) will still be marked as a valid +// value for the style (a falsy value implies that the style +// is to be removed at the end of the animation). If we had a simple +// "OR" statement then it would not be enough to catch that. +function registerRestorableStyles(backup, node, properties) { + forEach(properties, function(prop) { + backup[prop] = isDefined(backup[prop]) + ? backup[prop] + : node.style.getPropertyValue(prop); + }); +} + +var $AnimateCssProvider = ['$animateProvider', function($animateProvider) { + var gcsLookup = createLocalCacheLookup(); + var gcsStaggerLookup = createLocalCacheLookup(); + + this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout', + '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue', + function($window, $$jqLite, $$AnimateRunner, $timeout, + $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) { + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + var parentCounter = 0; + function gcsHashFn(node, extraClasses) { + var KEY = "$$ngAnimateParentKey"; + var parentNode = node.parentNode; + var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter); + return parentID + '-' + node.getAttribute('class') + '-' + extraClasses; + } + + function computeCachedCssStyles(node, className, cacheKey, properties) { + var timings = gcsLookup.get(cacheKey); + + if (!timings) { + timings = computeCssStyles($window, node, properties); + if (timings.animationIterationCount === 'infinite') { + timings.animationIterationCount = 1; + } + } + + // we keep putting this in multiple times even though the value and the cacheKey are the same + // because we're keeping an internal tally of how many duplicate animations are detected. + gcsLookup.put(cacheKey, timings); + return timings; + } + + function computeCachedCssStaggerStyles(node, className, cacheKey, properties) { + var stagger; + + // if we have one or more existing matches of matching elements + // containing the same parent + CSS styles (which is how cacheKey works) + // then staggering is possible + if (gcsLookup.count(cacheKey) > 0) { + stagger = gcsStaggerLookup.get(cacheKey); + + if (!stagger) { + var staggerClassName = pendClasses(className, '-stagger'); + + $$jqLite.addClass(node, staggerClassName); + + stagger = computeCssStyles($window, node, properties); + + // force the conversion of a null value to zero incase not set + stagger.animationDuration = Math.max(stagger.animationDuration, 0); + stagger.transitionDuration = Math.max(stagger.transitionDuration, 0); + + $$jqLite.removeClass(node, staggerClassName); + + gcsStaggerLookup.put(cacheKey, stagger); + } + } + + return stagger || {}; + } + + var cancelLastRAFRequest; + var rafWaitQueue = []; + function waitUntilQuiet(callback) { + rafWaitQueue.push(callback); + $$rAFScheduler.waitUntilQuiet(function() { + gcsLookup.flush(); + gcsStaggerLookup.flush(); + + // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable. + // PLEASE EXAMINE THE `$$forceReflow` service to understand why. + var pageWidth = $$forceReflow(); + + // we use a for loop to ensure that if the queue is changed + // during this looping then it will consider new requests + for (var i = 0; i < rafWaitQueue.length; i++) { + rafWaitQueue[i](pageWidth); + } + rafWaitQueue.length = 0; + }); + } + + function computeTimings(node, className, cacheKey) { + var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES); + var aD = timings.animationDelay; + var tD = timings.transitionDelay; + timings.maxDelay = aD && tD + ? Math.max(aD, tD) + : (aD || tD); + timings.maxDuration = Math.max( + timings.animationDuration * timings.animationIterationCount, + timings.transitionDuration); + + return timings; + } + + return function init(element, initialOptions) { + // all of the animation functions should create + // a copy of the options data, however, if a + // parent service has already created a copy then + // we should stick to using that + var options = initialOptions || {}; + if (!options.$$prepared) { + options = prepareAnimationOptions(copy(options)); + } + + var restoreStyles = {}; + var node = getDomNode(element); + if (!node + || !node.parentNode + || !$$animateQueue.enabled()) { + return closeAndReturnNoopAnimator(); + } + + var temporaryStyles = []; + var classes = element.attr('class'); + var styles = packageStyles(options); + var animationClosed; + var animationPaused; + var animationCompleted; + var runner; + var runnerHost; + var maxDelay; + var maxDelayTime; + var maxDuration; + var maxDurationTime; + var startTime; + var events = []; + + if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) { + return closeAndReturnNoopAnimator(); + } + + var method = options.event && isArray(options.event) + ? options.event.join(' ') + : options.event; + + var isStructural = method && options.structural; + var structuralClassName = ''; + var addRemoveClassName = ''; + + if (isStructural) { + structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true); + } else if (method) { + structuralClassName = method; + } + + if (options.addClass) { + addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX); + } + + if (options.removeClass) { + if (addRemoveClassName.length) { + addRemoveClassName += ' '; + } + addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX); + } + + // there may be a situation where a structural animation is combined together + // with CSS classes that need to resolve before the animation is computed. + // However this means that there is no explicit CSS code to block the animation + // from happening (by setting 0s none in the class name). If this is the case + // we need to apply the classes before the first rAF so we know to continue if + // there actually is a detected transition or keyframe animation + if (options.applyClassesEarly && addRemoveClassName.length) { + applyAnimationClasses(element, options); + } + + var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim(); + var fullClassName = classes + ' ' + preparationClasses; + var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX); + var hasToStyles = styles.to && Object.keys(styles.to).length > 0; + var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0; + + // there is no way we can trigger an animation if no styles and + // no classes are being applied which would then trigger a transition, + // unless there a is raw keyframe value that is applied to the element. + if (!containsKeyframeAnimation + && !hasToStyles + && !preparationClasses) { + return closeAndReturnNoopAnimator(); + } + + var cacheKey, stagger; + if (options.stagger > 0) { + var staggerVal = parseFloat(options.stagger); + stagger = { + transitionDelay: staggerVal, + animationDelay: staggerVal, + transitionDuration: 0, + animationDuration: 0 + }; + } else { + cacheKey = gcsHashFn(node, fullClassName); + stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES); + } + + if (!options.$$skipPreparationClasses) { + $$jqLite.addClass(element, preparationClasses); + } + + var applyOnlyDuration; + + if (options.transitionStyle) { + var transitionStyle = [TRANSITION_PROP, options.transitionStyle]; + applyInlineStyle(node, transitionStyle); + temporaryStyles.push(transitionStyle); + } + + if (options.duration >= 0) { + applyOnlyDuration = node.style[TRANSITION_PROP].length > 0; + var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration); + + // we set the duration so that it will be picked up by getComputedStyle later + applyInlineStyle(node, durationStyle); + temporaryStyles.push(durationStyle); + } + + if (options.keyframeStyle) { + var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle]; + applyInlineStyle(node, keyframeStyle); + temporaryStyles.push(keyframeStyle); + } + + var itemIndex = stagger + ? options.staggerIndex >= 0 + ? options.staggerIndex + : gcsLookup.count(cacheKey) + : 0; + + var isFirst = itemIndex === 0; + + // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY + // without causing any combination of transitions to kick in. By adding a negative delay value + // it forces the setup class' transition to end immediately. We later then remove the negative + // transition delay to allow for the transition to naturally do it's thing. The beauty here is + // that if there is no transition defined then nothing will happen and this will also allow + // other transitions to be stacked on top of each other without any chopping them out. + if (isFirst && !options.skipBlocking) { + blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE); + } + + var timings = computeTimings(node, fullClassName, cacheKey); + var relativeDelay = timings.maxDelay; + maxDelay = Math.max(relativeDelay, 0); + maxDuration = timings.maxDuration; + + var flags = {}; + flags.hasTransitions = timings.transitionDuration > 0; + flags.hasAnimations = timings.animationDuration > 0; + flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all'; + flags.applyTransitionDuration = hasToStyles && ( + (flags.hasTransitions && !flags.hasTransitionAll) + || (flags.hasAnimations && !flags.hasTransitions)); + flags.applyAnimationDuration = options.duration && flags.hasAnimations; + flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions); + flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations; + flags.recalculateTimingStyles = addRemoveClassName.length > 0; + + if (flags.applyTransitionDuration || flags.applyAnimationDuration) { + maxDuration = options.duration ? parseFloat(options.duration) : maxDuration; + + if (flags.applyTransitionDuration) { + flags.hasTransitions = true; + timings.transitionDuration = maxDuration; + applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0; + temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration)); + } + + if (flags.applyAnimationDuration) { + flags.hasAnimations = true; + timings.animationDuration = maxDuration; + temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration)); + } + } + + if (maxDuration === 0 && !flags.recalculateTimingStyles) { + return closeAndReturnNoopAnimator(); + } + + if (options.delay != null) { + var delayStyle; + if (typeof options.delay !== "boolean") { + delayStyle = parseFloat(options.delay); + // number in options.delay means we have to recalculate the delay for the closing timeout + maxDelay = Math.max(delayStyle, 0); + } + + if (flags.applyTransitionDelay) { + temporaryStyles.push(getCssDelayStyle(delayStyle)); + } + + if (flags.applyAnimationDelay) { + temporaryStyles.push(getCssDelayStyle(delayStyle, true)); + } + } + + // we need to recalculate the delay value since we used a pre-emptive negative + // delay value and the delay value is required for the final event checking. This + // property will ensure that this will happen after the RAF phase has passed. + if (options.duration == null && timings.transitionDuration > 0) { + flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst; + } + + maxDelayTime = maxDelay * ONE_SECOND; + maxDurationTime = maxDuration * ONE_SECOND; + if (!options.skipBlocking) { + flags.blockTransition = timings.transitionDuration > 0; + flags.blockKeyframeAnimation = timings.animationDuration > 0 && + stagger.animationDelay > 0 && + stagger.animationDuration === 0; + } + + if (options.from) { + if (options.cleanupStyles) { + registerRestorableStyles(restoreStyles, node, Object.keys(options.from)); + } + applyAnimationFromStyles(element, options); + } + + if (flags.blockTransition || flags.blockKeyframeAnimation) { + applyBlocking(maxDuration); + } else if (!options.skipBlocking) { + blockTransitions(node, false); + } + + // TODO(matsko): for 1.5 change this code to have an animator object for better debugging + return { + $$willAnimate: true, + end: endFn, + start: function() { + if (animationClosed) return; + + runnerHost = { + end: endFn, + cancel: cancelFn, + resume: null, //this will be set during the start() phase + pause: null + }; + + runner = new $$AnimateRunner(runnerHost); + + waitUntilQuiet(start); + + // we don't have access to pause/resume the animation + // since it hasn't run yet. AnimateRunner will therefore + // set noop functions for resume and pause and they will + // later be overridden once the animation is triggered + return runner; + } + }; + + function endFn() { + close(); + } + + function cancelFn() { + close(true); + } + + function close(rejected) { // jshint ignore:line + // if the promise has been called already then we shouldn't close + // the animation again + if (animationClosed || (animationCompleted && animationPaused)) return; + animationClosed = true; + animationPaused = false; + + if (!options.$$skipPreparationClasses) { + $$jqLite.removeClass(element, preparationClasses); + } + $$jqLite.removeClass(element, activeClasses); + + blockKeyframeAnimations(node, false); + blockTransitions(node, false); + + forEach(temporaryStyles, function(entry) { + // There is only one way to remove inline style properties entirely from elements. + // By using `removeProperty` this works, but we need to convert camel-cased CSS + // styles down to hyphenated values. + node.style[entry[0]] = ''; + }); + + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + + if (Object.keys(restoreStyles).length) { + forEach(restoreStyles, function(value, prop) { + value ? node.style.setProperty(prop, value) + : node.style.removeProperty(prop); + }); + } + + // the reason why we have this option is to allow a synchronous closing callback + // that is fired as SOON as the animation ends (when the CSS is removed) or if + // the animation never takes off at all. A good example is a leave animation since + // the element must be removed just after the animation is over or else the element + // will appear on screen for one animation frame causing an overbearing flicker. + if (options.onDone) { + options.onDone(); + } + + if (events && events.length) { + // Remove the transitionend / animationend listener(s) + element.off(events.join(' '), onAnimationProgress); + } + + //Cancel the fallback closing timeout and remove the timer data + var animationTimerData = element.data(ANIMATE_TIMER_KEY); + if (animationTimerData) { + $timeout.cancel(animationTimerData[0].timer); + element.removeData(ANIMATE_TIMER_KEY); + } + + // if the preparation function fails then the promise is not setup + if (runner) { + runner.complete(!rejected); + } + } + + function applyBlocking(duration) { + if (flags.blockTransition) { + blockTransitions(node, duration); + } + + if (flags.blockKeyframeAnimation) { + blockKeyframeAnimations(node, !!duration); + } + } + + function closeAndReturnNoopAnimator() { + runner = new $$AnimateRunner({ + end: endFn, + cancel: cancelFn + }); + + // should flush the cache animation + waitUntilQuiet(noop); + close(); + + return { + $$willAnimate: false, + start: function() { + return runner; + }, + end: endFn + }; + } + + function onAnimationProgress(event) { + event.stopPropagation(); + var ev = event.originalEvent || event; + + // we now always use `Date.now()` due to the recent changes with + // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info) + var timeStamp = ev.$manualTimeStamp || Date.now(); + + /* Firefox (or possibly just Gecko) likes to not round values up + * when a ms measurement is used for the animation */ + var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); + + /* $manualTimeStamp is a mocked timeStamp value which is set + * within browserTrigger(). This is only here so that tests can + * mock animations properly. Real events fallback to event.timeStamp, + * or, if they don't, then a timeStamp is automatically created for them. + * We're checking to see if the timeStamp surpasses the expected delay, + * but we're using elapsedTime instead of the timeStamp on the 2nd + * pre-condition since animationPauseds sometimes close off early */ + if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { + // we set this flag to ensure that if the transition is paused then, when resumed, + // the animation will automatically close itself since transitions cannot be paused. + animationCompleted = true; + close(); + } + } + + function start() { + if (animationClosed) return; + if (!node.parentNode) { + close(); + return; + } + + // even though we only pause keyframe animations here the pause flag + // will still happen when transitions are used. Only the transition will + // not be paused since that is not possible. If the animation ends when + // paused then it will not complete until unpaused or cancelled. + var playPause = function(playAnimation) { + if (!animationCompleted) { + animationPaused = !playAnimation; + if (timings.animationDuration) { + var value = blockKeyframeAnimations(node, animationPaused); + animationPaused + ? temporaryStyles.push(value) + : removeFromArray(temporaryStyles, value); + } + } else if (animationPaused && playAnimation) { + animationPaused = false; + close(); + } + }; + + // checking the stagger duration prevents an accidentally cascade of the CSS delay style + // being inherited from the parent. If the transition duration is zero then we can safely + // rely that the delay value is an intentional stagger delay style. + var maxStagger = itemIndex > 0 + && ((timings.transitionDuration && stagger.transitionDuration === 0) || + (timings.animationDuration && stagger.animationDuration === 0)) + && Math.max(stagger.animationDelay, stagger.transitionDelay); + if (maxStagger) { + $timeout(triggerAnimationStart, + Math.floor(maxStagger * itemIndex * ONE_SECOND), + false); + } else { + triggerAnimationStart(); + } + + // this will decorate the existing promise runner with pause/resume methods + runnerHost.resume = function() { + playPause(true); + }; + + runnerHost.pause = function() { + playPause(false); + }; + + function triggerAnimationStart() { + // just incase a stagger animation kicks in when the animation + // itself was cancelled entirely + if (animationClosed) return; + + applyBlocking(false); + + forEach(temporaryStyles, function(entry) { + var key = entry[0]; + var value = entry[1]; + node.style[key] = value; + }); + + applyAnimationClasses(element, options); + $$jqLite.addClass(element, activeClasses); + + if (flags.recalculateTimingStyles) { + fullClassName = node.className + ' ' + preparationClasses; + cacheKey = gcsHashFn(node, fullClassName); + + timings = computeTimings(node, fullClassName, cacheKey); + relativeDelay = timings.maxDelay; + maxDelay = Math.max(relativeDelay, 0); + maxDuration = timings.maxDuration; + + if (maxDuration === 0) { + close(); + return; + } + + flags.hasTransitions = timings.transitionDuration > 0; + flags.hasAnimations = timings.animationDuration > 0; + } + + if (flags.applyAnimationDelay) { + relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay) + ? parseFloat(options.delay) + : relativeDelay; + + maxDelay = Math.max(relativeDelay, 0); + timings.animationDelay = relativeDelay; + delayStyle = getCssDelayStyle(relativeDelay, true); + temporaryStyles.push(delayStyle); + node.style[delayStyle[0]] = delayStyle[1]; + } + + maxDelayTime = maxDelay * ONE_SECOND; + maxDurationTime = maxDuration * ONE_SECOND; + + if (options.easing) { + var easeProp, easeVal = options.easing; + if (flags.hasTransitions) { + easeProp = TRANSITION_PROP + TIMING_KEY; + temporaryStyles.push([easeProp, easeVal]); + node.style[easeProp] = easeVal; + } + if (flags.hasAnimations) { + easeProp = ANIMATION_PROP + TIMING_KEY; + temporaryStyles.push([easeProp, easeVal]); + node.style[easeProp] = easeVal; + } + } + + if (timings.transitionDuration) { + events.push(TRANSITIONEND_EVENT); + } + + if (timings.animationDuration) { + events.push(ANIMATIONEND_EVENT); + } + + startTime = Date.now(); + var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime; + var endTime = startTime + timerTime; + + var animationsData = element.data(ANIMATE_TIMER_KEY) || []; + var setupFallbackTimer = true; + if (animationsData.length) { + var currentTimerData = animationsData[0]; + setupFallbackTimer = endTime > currentTimerData.expectedEndTime; + if (setupFallbackTimer) { + $timeout.cancel(currentTimerData.timer); + } else { + animationsData.push(close); + } + } + + if (setupFallbackTimer) { + var timer = $timeout(onAnimationExpired, timerTime, false); + animationsData[0] = { + timer: timer, + expectedEndTime: endTime + }; + animationsData.push(close); + element.data(ANIMATE_TIMER_KEY, animationsData); + } + + if (events.length) { + element.on(events.join(' '), onAnimationProgress); + } + + if (options.to) { + if (options.cleanupStyles) { + registerRestorableStyles(restoreStyles, node, Object.keys(options.to)); + } + applyAnimationToStyles(element, options); + } + } + + function onAnimationExpired() { + var animationsData = element.data(ANIMATE_TIMER_KEY); + + // this will be false in the event that the element was + // removed from the DOM (via a leave animation or something + // similar) + if (animationsData) { + for (var i = 1; i < animationsData.length; i++) { + animationsData[i](); + } + element.removeData(ANIMATE_TIMER_KEY); + } + } + } + }; + }]; +}]; + +var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) { + $$animationProvider.drivers.push('$$animateCssDriver'); + + var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim'; + var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor'; + + var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out'; + var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in'; + + function isDocumentFragment(node) { + return node.parentNode && node.parentNode.nodeType === 11; + } + + this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document', + function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) { + + // only browsers that support these properties can render animations + if (!$sniffer.animations && !$sniffer.transitions) return noop; + + var bodyNode = $document[0].body; + var rootNode = getDomNode($rootElement); + + var rootBodyElement = jqLite( + // this is to avoid using something that exists outside of the body + // we also special case the doc fragment case because our unit test code + // appends the $rootElement to the body after the app has been bootstrapped + isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode + ); + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + return function initDriverFn(animationDetails) { + return animationDetails.from && animationDetails.to + ? prepareFromToAnchorAnimation(animationDetails.from, + animationDetails.to, + animationDetails.classes, + animationDetails.anchors) + : prepareRegularAnimation(animationDetails); + }; + + function filterCssClasses(classes) { + //remove all the `ng-` stuff + return classes.replace(/\bng-\S+\b/g, ''); + } + + function getUniqueValues(a, b) { + if (isString(a)) a = a.split(' '); + if (isString(b)) b = b.split(' '); + return a.filter(function(val) { + return b.indexOf(val) === -1; + }).join(' '); + } + + function prepareAnchoredAnimation(classes, outAnchor, inAnchor) { + var clone = jqLite(getDomNode(outAnchor).cloneNode(true)); + var startingClasses = filterCssClasses(getClassVal(clone)); + + outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME); + inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME); + + clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME); + + rootBodyElement.append(clone); + + var animatorIn, animatorOut = prepareOutAnimation(); + + // the user may not end up using the `out` animation and + // only making use of the `in` animation or vice-versa. + // In either case we should allow this and not assume the + // animation is over unless both animations are not used. + if (!animatorOut) { + animatorIn = prepareInAnimation(); + if (!animatorIn) { + return end(); + } + } + + var startingAnimator = animatorOut || animatorIn; + + return { + start: function() { + var runner; + + var currentAnimation = startingAnimator.start(); + currentAnimation.done(function() { + currentAnimation = null; + if (!animatorIn) { + animatorIn = prepareInAnimation(); + if (animatorIn) { + currentAnimation = animatorIn.start(); + currentAnimation.done(function() { + currentAnimation = null; + end(); + runner.complete(); + }); + return currentAnimation; + } + } + // in the event that there is no `in` animation + end(); + runner.complete(); + }); + + runner = new $$AnimateRunner({ + end: endFn, + cancel: endFn + }); + + return runner; + + function endFn() { + if (currentAnimation) { + currentAnimation.end(); + } + } + } + }; + + function calculateAnchorStyles(anchor) { + var styles = {}; + + var coords = getDomNode(anchor).getBoundingClientRect(); + + // we iterate directly since safari messes up and doesn't return + // all the keys for the coords object when iterated + forEach(['width','height','top','left'], function(key) { + var value = coords[key]; + switch (key) { + case 'top': + value += bodyNode.scrollTop; + break; + case 'left': + value += bodyNode.scrollLeft; + break; + } + styles[key] = Math.floor(value) + 'px'; + }); + return styles; + } + + function prepareOutAnimation() { + var animator = $animateCss(clone, { + addClass: NG_OUT_ANCHOR_CLASS_NAME, + delay: true, + from: calculateAnchorStyles(outAnchor) + }); + + // read the comment within `prepareRegularAnimation` to understand + // why this check is necessary + return animator.$$willAnimate ? animator : null; + } + + function getClassVal(element) { + return element.attr('class') || ''; + } + + function prepareInAnimation() { + var endingClasses = filterCssClasses(getClassVal(inAnchor)); + var toAdd = getUniqueValues(endingClasses, startingClasses); + var toRemove = getUniqueValues(startingClasses, endingClasses); + + var animator = $animateCss(clone, { + to: calculateAnchorStyles(inAnchor), + addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd, + removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove, + delay: true + }); + + // read the comment within `prepareRegularAnimation` to understand + // why this check is necessary + return animator.$$willAnimate ? animator : null; + } + + function end() { + clone.remove(); + outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME); + inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME); + } + } + + function prepareFromToAnchorAnimation(from, to, classes, anchors) { + var fromAnimation = prepareRegularAnimation(from, noop); + var toAnimation = prepareRegularAnimation(to, noop); + + var anchorAnimations = []; + forEach(anchors, function(anchor) { + var outElement = anchor['out']; + var inElement = anchor['in']; + var animator = prepareAnchoredAnimation(classes, outElement, inElement); + if (animator) { + anchorAnimations.push(animator); + } + }); + + // no point in doing anything when there are no elements to animate + if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return; + + return { + start: function() { + var animationRunners = []; + + if (fromAnimation) { + animationRunners.push(fromAnimation.start()); + } + + if (toAnimation) { + animationRunners.push(toAnimation.start()); + } + + forEach(anchorAnimations, function(animation) { + animationRunners.push(animation.start()); + }); + + var runner = new $$AnimateRunner({ + end: endFn, + cancel: endFn // CSS-driven animations cannot be cancelled, only ended + }); + + $$AnimateRunner.all(animationRunners, function(status) { + runner.complete(status); + }); + + return runner; + + function endFn() { + forEach(animationRunners, function(runner) { + runner.end(); + }); + } + } + }; + } + + function prepareRegularAnimation(animationDetails) { + var element = animationDetails.element; + var options = animationDetails.options || {}; + + if (animationDetails.structural) { + options.event = animationDetails.event; + options.structural = true; + options.applyClassesEarly = true; + + // we special case the leave animation since we want to ensure that + // the element is removed as soon as the animation is over. Otherwise + // a flicker might appear or the element may not be removed at all + if (animationDetails.event === 'leave') { + options.onDone = options.domOperation; + } + } + + // We assign the preparationClasses as the actual animation event since + // the internals of $animateCss will just suffix the event token values + // with `-active` to trigger the animation. + if (options.preparationClasses) { + options.event = concatWithSpace(options.event, options.preparationClasses); + } + + var animator = $animateCss(element, options); + + // the driver lookup code inside of $$animation attempts to spawn a + // driver one by one until a driver returns a.$$willAnimate animator object. + // $animateCss will always return an object, however, it will pass in + // a flag as a hint as to whether an animation was detected or not + return animator.$$willAnimate ? animator : null; + } + }]; +}]; + +// TODO(matsko): use caching here to speed things up for detection +// TODO(matsko): add documentation +// by the time... + +var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) { + this.$get = ['$injector', '$$AnimateRunner', '$$jqLite', + function($injector, $$AnimateRunner, $$jqLite) { + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + // $animateJs(element, 'enter'); + return function(element, event, classes, options) { + var animationClosed = false; + + // the `classes` argument is optional and if it is not used + // then the classes will be resolved from the element's className + // property as well as options.addClass/options.removeClass. + if (arguments.length === 3 && isObject(classes)) { + options = classes; + classes = null; + } + + options = prepareAnimationOptions(options); + if (!classes) { + classes = element.attr('class') || ''; + if (options.addClass) { + classes += ' ' + options.addClass; + } + if (options.removeClass) { + classes += ' ' + options.removeClass; + } + } + + var classesToAdd = options.addClass; + var classesToRemove = options.removeClass; + + // the lookupAnimations function returns a series of animation objects that are + // matched up with one or more of the CSS classes. These animation objects are + // defined via the module.animation factory function. If nothing is detected then + // we don't return anything which then makes $animation query the next driver. + var animations = lookupAnimations(classes); + var before, after; + if (animations.length) { + var afterFn, beforeFn; + if (event == 'leave') { + beforeFn = 'leave'; + afterFn = 'afterLeave'; // TODO(matsko): get rid of this + } else { + beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1); + afterFn = event; + } + + if (event !== 'enter' && event !== 'move') { + before = packageAnimations(element, event, options, animations, beforeFn); + } + after = packageAnimations(element, event, options, animations, afterFn); + } + + // no matching animations + if (!before && !after) return; + + function applyOptions() { + options.domOperation(); + applyAnimationClasses(element, options); + } + + function close() { + animationClosed = true; + applyOptions(); + applyAnimationStyles(element, options); + } + + var runner; + + return { + $$willAnimate: true, + end: function() { + if (runner) { + runner.end(); + } else { + close(); + runner = new $$AnimateRunner(); + runner.complete(true); + } + return runner; + }, + start: function() { + if (runner) { + return runner; + } + + runner = new $$AnimateRunner(); + var closeActiveAnimations; + var chain = []; + + if (before) { + chain.push(function(fn) { + closeActiveAnimations = before(fn); + }); + } + + if (chain.length) { + chain.push(function(fn) { + applyOptions(); + fn(true); + }); + } else { + applyOptions(); + } + + if (after) { + chain.push(function(fn) { + closeActiveAnimations = after(fn); + }); + } + + runner.setHost({ + end: function() { + endAnimations(); + }, + cancel: function() { + endAnimations(true); + } + }); + + $$AnimateRunner.chain(chain, onComplete); + return runner; + + function onComplete(success) { + close(success); + runner.complete(success); + } + + function endAnimations(cancelled) { + if (!animationClosed) { + (closeActiveAnimations || noop)(cancelled); + onComplete(cancelled); + } + } + } + }; + + function executeAnimationFn(fn, element, event, options, onDone) { + var args; + switch (event) { + case 'animate': + args = [element, options.from, options.to, onDone]; + break; + + case 'setClass': + args = [element, classesToAdd, classesToRemove, onDone]; + break; + + case 'addClass': + args = [element, classesToAdd, onDone]; + break; + + case 'removeClass': + args = [element, classesToRemove, onDone]; + break; + + default: + args = [element, onDone]; + break; + } + + args.push(options); + + var value = fn.apply(fn, args); + if (value) { + if (isFunction(value.start)) { + value = value.start(); + } + + if (value instanceof $$AnimateRunner) { + value.done(onDone); + } else if (isFunction(value)) { + // optional onEnd / onCancel callback + return value; + } + } + + return noop; + } + + function groupEventedAnimations(element, event, options, animations, fnName) { + var operations = []; + forEach(animations, function(ani) { + var animation = ani[fnName]; + if (!animation) return; + + // note that all of these animations will run in parallel + operations.push(function() { + var runner; + var endProgressCb; + + var resolved = false; + var onAnimationComplete = function(rejected) { + if (!resolved) { + resolved = true; + (endProgressCb || noop)(rejected); + runner.complete(!rejected); + } + }; + + runner = new $$AnimateRunner({ + end: function() { + onAnimationComplete(); + }, + cancel: function() { + onAnimationComplete(true); + } + }); + + endProgressCb = executeAnimationFn(animation, element, event, options, function(result) { + var cancelled = result === false; + onAnimationComplete(cancelled); + }); + + return runner; + }); + }); + + return operations; + } + + function packageAnimations(element, event, options, animations, fnName) { + var operations = groupEventedAnimations(element, event, options, animations, fnName); + if (operations.length === 0) { + var a,b; + if (fnName === 'beforeSetClass') { + a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass'); + b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass'); + } else if (fnName === 'setClass') { + a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass'); + b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass'); + } + + if (a) { + operations = operations.concat(a); + } + if (b) { + operations = operations.concat(b); + } + } + + if (operations.length === 0) return; + + // TODO(matsko): add documentation + return function startAnimation(callback) { + var runners = []; + if (operations.length) { + forEach(operations, function(animateFn) { + runners.push(animateFn()); + }); + } + + runners.length ? $$AnimateRunner.all(runners, callback) : callback(); + + return function endFn(reject) { + forEach(runners, function(runner) { + reject ? runner.cancel() : runner.end(); + }); + }; + }; + } + }; + + function lookupAnimations(classes) { + classes = isArray(classes) ? classes : classes.split(' '); + var matches = [], flagMap = {}; + for (var i=0; i < classes.length; i++) { + var klass = classes[i], + animationFactory = $animateProvider.$$registeredAnimations[klass]; + if (animationFactory && !flagMap[klass]) { + matches.push($injector.get(animationFactory)); + flagMap[klass] = true; + } + } + return matches; + } + }]; +}]; + +var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) { + $$animationProvider.drivers.push('$$animateJsDriver'); + this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) { + return function initDriverFn(animationDetails) { + if (animationDetails.from && animationDetails.to) { + var fromAnimation = prepareAnimation(animationDetails.from); + var toAnimation = prepareAnimation(animationDetails.to); + if (!fromAnimation && !toAnimation) return; + + return { + start: function() { + var animationRunners = []; + + if (fromAnimation) { + animationRunners.push(fromAnimation.start()); + } + + if (toAnimation) { + animationRunners.push(toAnimation.start()); + } + + $$AnimateRunner.all(animationRunners, done); + + var runner = new $$AnimateRunner({ + end: endFnFactory(), + cancel: endFnFactory() + }); + + return runner; + + function endFnFactory() { + return function() { + forEach(animationRunners, function(runner) { + // at this point we cannot cancel animations for groups just yet. 1.5+ + runner.end(); + }); + }; + } + + function done(status) { + runner.complete(status); + } + } + }; + } else { + return prepareAnimation(animationDetails); + } + }; + + function prepareAnimation(animationDetails) { + // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations + var element = animationDetails.element; + var event = animationDetails.event; + var options = animationDetails.options; + var classes = animationDetails.classes; + return $$animateJs(element, event, classes, options); + } + }]; +}]; + +var NG_ANIMATE_ATTR_NAME = 'data-ng-animate'; +var NG_ANIMATE_PIN_DATA = '$ngAnimatePin'; +var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) { + var PRE_DIGEST_STATE = 1; + var RUNNING_STATE = 2; + var ONE_SPACE = ' '; + + var rules = this.rules = { + skip: [], + cancel: [], + join: [] + }; + + function makeTruthyCssClassMap(classString) { + if (!classString) { + return null; + } + + var keys = classString.split(ONE_SPACE); + var map = Object.create(null); + + forEach(keys, function(key) { + map[key] = true; + }); + return map; + } + + function hasMatchingClasses(newClassString, currentClassString) { + if (newClassString && currentClassString) { + var currentClassMap = makeTruthyCssClassMap(currentClassString); + return newClassString.split(ONE_SPACE).some(function(className) { + return currentClassMap[className]; + }); + } + } + + function isAllowed(ruleType, element, currentAnimation, previousAnimation) { + return rules[ruleType].some(function(fn) { + return fn(element, currentAnimation, previousAnimation); + }); + } + + function hasAnimationClasses(animation, and) { + var a = (animation.addClass || '').length > 0; + var b = (animation.removeClass || '').length > 0; + return and ? a && b : a || b; + } + + rules.join.push(function(element, newAnimation, currentAnimation) { + // if the new animation is class-based then we can just tack that on + return !newAnimation.structural && hasAnimationClasses(newAnimation); + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // there is no need to animate anything if no classes are being added and + // there is no structural animation that will be triggered + return !newAnimation.structural && !hasAnimationClasses(newAnimation); + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // why should we trigger a new structural animation if the element will + // be removed from the DOM anyway? + return currentAnimation.event == 'leave' && newAnimation.structural; + }); + + rules.skip.push(function(element, newAnimation, currentAnimation) { + // if there is an ongoing current animation then don't even bother running the class-based animation + return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // there can never be two structural animations running at the same time + return currentAnimation.structural && newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // if the previous animation is already running, but the new animation will + // be triggered, but the new animation is structural + return currentAnimation.state === RUNNING_STATE && newAnimation.structural; + }); + + rules.cancel.push(function(element, newAnimation, currentAnimation) { + // cancel the animation if classes added / removed in both animation cancel each other out, + // but only if the current animation isn't structural + + if (currentAnimation.structural) return false; + + var nA = newAnimation.addClass; + var nR = newAnimation.removeClass; + var cA = currentAnimation.addClass; + var cR = currentAnimation.removeClass; + + // early detection to save the global CPU shortage :) + if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) { + return false; + } + + return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA); + }); + + this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap', + '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow', + function($$rAF, $rootScope, $rootElement, $document, $$HashMap, + $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) { + + var activeAnimationsLookup = new $$HashMap(); + var disabledElementsLookup = new $$HashMap(); + var animationsEnabled = null; + + function postDigestTaskFactory() { + var postDigestCalled = false; + return function(fn) { + // we only issue a call to postDigest before + // it has first passed. This prevents any callbacks + // from not firing once the animation has completed + // since it will be out of the digest cycle. + if (postDigestCalled) { + fn(); + } else { + $rootScope.$$postDigest(function() { + postDigestCalled = true; + fn(); + }); + } + }; + } + + // Wait until all directive and route-related templates are downloaded and + // compiled. The $templateRequest.totalPendingRequests variable keeps track of + // all of the remote templates being currently downloaded. If there are no + // templates currently downloading then the watcher will still fire anyway. + var deregisterWatch = $rootScope.$watch( + function() { return $templateRequest.totalPendingRequests === 0; }, + function(isEmpty) { + if (!isEmpty) return; + deregisterWatch(); + + // Now that all templates have been downloaded, $animate will wait until + // the post digest queue is empty before enabling animations. By having two + // calls to $postDigest calls we can ensure that the flag is enabled at the + // very end of the post digest queue. Since all of the animations in $animate + // use $postDigest, it's important that the code below executes at the end. + // This basically means that the page is fully downloaded and compiled before + // any animations are triggered. + $rootScope.$$postDigest(function() { + $rootScope.$$postDigest(function() { + // we check for null directly in the event that the application already called + // .enabled() with whatever arguments that it provided it with + if (animationsEnabled === null) { + animationsEnabled = true; + } + }); + }); + } + ); + + var callbackRegistry = Object.create(null); + + // remember that the classNameFilter is set during the provider/config + // stage therefore we can optimize here and setup a helper function + var classNameFilter = $animateProvider.classNameFilter(); + var isAnimatableClassName = !classNameFilter + ? function() { return true; } + : function(className) { + return classNameFilter.test(className); + }; + + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + function normalizeAnimationDetails(element, animation) { + return mergeAnimationDetails(element, animation, {}); + } + + // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259. + var contains = window.Node.prototype.contains || function(arg) { + // jshint bitwise: false + return this === arg || !!(this.compareDocumentPosition(arg) & 16); + // jshint bitwise: true + }; + + function findCallbacks(parent, element, event) { + var targetNode = getDomNode(element); + var targetParentNode = getDomNode(parent); + + var matches = []; + var entries = callbackRegistry[event]; + if (entries) { + forEach(entries, function(entry) { + if (contains.call(entry.node, targetNode)) { + matches.push(entry.callback); + } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) { + matches.push(entry.callback); + } + }); + } + + return matches; + } + + function filterFromRegistry(list, matchContainer, matchCallback) { + var containerNode = extractElementNode(matchContainer); + return list.filter(function(entry) { + var isMatch = entry.node === containerNode && + (!matchCallback || entry.callback === matchCallback); + return !isMatch; + }); + } + + function cleanupEventListeners(phase, element) { + if (phase === 'close' && !element[0].parentNode) { + // If the element is not attached to a parentNode, it has been removed by + // the domOperation, and we can safely remove the event callbacks + $animate.off(element); + } + } + + var $animate = { + on: function(event, container, callback) { + var node = extractElementNode(container); + callbackRegistry[event] = callbackRegistry[event] || []; + callbackRegistry[event].push({ + node: node, + callback: callback + }); + + // Remove the callback when the element is removed from the DOM + jqLite(container).on('$destroy', function() { + var animationDetails = activeAnimationsLookup.get(node); + + if (!animationDetails) { + // If there's an animation ongoing, the callback calling code will remove + // the event listeners. If we'd remove here, the callbacks would be removed + // before the animation ends + $animate.off(event, container, callback); + } + }); + }, + + off: function(event, container, callback) { + if (arguments.length === 1 && !isString(arguments[0])) { + container = arguments[0]; + for (var eventType in callbackRegistry) { + callbackRegistry[eventType] = filterFromRegistry(callbackRegistry[eventType], container); + } + + return; + } + + var entries = callbackRegistry[event]; + if (!entries) return; + + callbackRegistry[event] = arguments.length === 1 + ? null + : filterFromRegistry(entries, container, callback); + }, + + pin: function(element, parentElement) { + assertArg(isElement(element), 'element', 'not an element'); + assertArg(isElement(parentElement), 'parentElement', 'not an element'); + element.data(NG_ANIMATE_PIN_DATA, parentElement); + }, + + push: function(element, event, options, domOperation) { + options = options || {}; + options.domOperation = domOperation; + return queueAnimation(element, event, options); + }, + + // this method has four signatures: + // () - global getter + // (bool) - global setter + // (element) - element getter + // (element, bool) - element setter + enabled: function(element, bool) { + var argCount = arguments.length; + + if (argCount === 0) { + // () - Global getter + bool = !!animationsEnabled; + } else { + var hasElement = isElement(element); + + if (!hasElement) { + // (bool) - Global setter + bool = animationsEnabled = !!element; + } else { + var node = getDomNode(element); + + if (argCount === 1) { + // (element) - Element getter + bool = !disabledElementsLookup.get(node); + } else { + // (element, bool) - Element setter + disabledElementsLookup.put(node, !bool); + } + } + } + + return bool; + } + }; + + return $animate; + + function queueAnimation(element, event, initialOptions) { + // we always make a copy of the options since + // there should never be any side effects on + // the input data when running `$animateCss`. + var options = copy(initialOptions); + + var node, parent; + element = stripCommentsFromElement(element); + if (element) { + node = getDomNode(element); + parent = element.parent(); + } + + options = prepareAnimationOptions(options); + + // we create a fake runner with a working promise. + // These methods will become available after the digest has passed + var runner = new $$AnimateRunner(); + + // this is used to trigger callbacks in postDigest mode + var runInNextPostDigestOrNow = postDigestTaskFactory(); + + if (isArray(options.addClass)) { + options.addClass = options.addClass.join(' '); + } + + if (options.addClass && !isString(options.addClass)) { + options.addClass = null; + } + + if (isArray(options.removeClass)) { + options.removeClass = options.removeClass.join(' '); + } + + if (options.removeClass && !isString(options.removeClass)) { + options.removeClass = null; + } + + if (options.from && !isObject(options.from)) { + options.from = null; + } + + if (options.to && !isObject(options.to)) { + options.to = null; + } + + // there are situations where a directive issues an animation for + // a jqLite wrapper that contains only comment nodes... If this + // happens then there is no way we can perform an animation + if (!node) { + close(); + return runner; + } + + var className = [node.className, options.addClass, options.removeClass].join(' '); + if (!isAnimatableClassName(className)) { + close(); + return runner; + } + + var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0; + + var documentHidden = $document[0].hidden; + + // this is a hard disable of all animations for the application or on + // the element itself, therefore there is no need to continue further + // past this point if not enabled + // Animations are also disabled if the document is currently hidden (page is not visible + // to the user), because browsers slow down or do not flush calls to requestAnimationFrame + var skipAnimations = !animationsEnabled || documentHidden || disabledElementsLookup.get(node); + var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {}; + var hasExistingAnimation = !!existingAnimation.state; + + // there is no point in traversing the same collection of parent ancestors if a followup + // animation will be run on the same element that already did all that checking work + if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) { + skipAnimations = !areAnimationsAllowed(element, parent, event); + } + + if (skipAnimations) { + // Callbacks should fire even if the document is hidden (regression fix for issue #14120) + if (documentHidden) notifyProgress(runner, event, 'start'); + close(); + if (documentHidden) notifyProgress(runner, event, 'close'); + return runner; + } + + if (isStructural) { + closeChildAnimations(element); + } + + var newAnimation = { + structural: isStructural, + element: element, + event: event, + addClass: options.addClass, + removeClass: options.removeClass, + close: close, + options: options, + runner: runner + }; + + if (hasExistingAnimation) { + var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation); + if (skipAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + close(); + return runner; + } else { + mergeAnimationDetails(element, existingAnimation, newAnimation); + return existingAnimation.runner; + } + } + var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation); + if (cancelAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + // this will end the animation right away and it is safe + // to do so since the animation is already running and the + // runner callback code will run in async + existingAnimation.runner.end(); + } else if (existingAnimation.structural) { + // this means that the animation is queued into a digest, but + // hasn't started yet. Therefore it is safe to run the close + // method which will call the runner methods in async. + existingAnimation.close(); + } else { + // this will merge the new animation options into existing animation options + mergeAnimationDetails(element, existingAnimation, newAnimation); + + return existingAnimation.runner; + } + } else { + // a joined animation means that this animation will take over the existing one + // so an example would involve a leave animation taking over an enter. Then when + // the postDigest kicks in the enter will be ignored. + var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation); + if (joinAnimationFlag) { + if (existingAnimation.state === RUNNING_STATE) { + normalizeAnimationDetails(element, newAnimation); + } else { + applyGeneratedPreparationClasses(element, isStructural ? event : null, options); + + event = newAnimation.event = existingAnimation.event; + options = mergeAnimationDetails(element, existingAnimation, newAnimation); + + //we return the same runner since only the option values of this animation will + //be fed into the `existingAnimation`. + return existingAnimation.runner; + } + } + } + } else { + // normalization in this case means that it removes redundant CSS classes that + // already exist (addClass) or do not exist (removeClass) on the element + normalizeAnimationDetails(element, newAnimation); + } + + // when the options are merged and cleaned up we may end up not having to do + // an animation at all, therefore we should check this before issuing a post + // digest callback. Structural animations will always run no matter what. + var isValidAnimation = newAnimation.structural; + if (!isValidAnimation) { + // animate (from/to) can be quickly checked first, otherwise we check if any classes are present + isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0) + || hasAnimationClasses(newAnimation); + } + + if (!isValidAnimation) { + close(); + clearElementAnimationState(element); + return runner; + } + + // the counter keeps track of cancelled animations + var counter = (existingAnimation.counter || 0) + 1; + newAnimation.counter = counter; + + markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation); + + $rootScope.$$postDigest(function() { + var animationDetails = activeAnimationsLookup.get(node); + var animationCancelled = !animationDetails; + animationDetails = animationDetails || {}; + + // if addClass/removeClass is called before something like enter then the + // registered parent element may not be present. The code below will ensure + // that a final value for parent element is obtained + var parentElement = element.parent() || []; + + // animate/structural/class-based animations all have requirements. Otherwise there + // is no point in performing an animation. The parent node must also be set. + var isValidAnimation = parentElement.length > 0 + && (animationDetails.event === 'animate' + || animationDetails.structural + || hasAnimationClasses(animationDetails)); + + // this means that the previous animation was cancelled + // even if the follow-up animation is the same event + if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) { + // if another animation did not take over then we need + // to make sure that the domOperation and options are + // handled accordingly + if (animationCancelled) { + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + } + + // if the event changed from something like enter to leave then we do + // it, otherwise if it's the same then the end result will be the same too + if (animationCancelled || (isStructural && animationDetails.event !== event)) { + options.domOperation(); + runner.end(); + } + + // in the event that the element animation was not cancelled or a follow-up animation + // isn't allowed to animate from here then we need to clear the state of the element + // so that any future animations won't read the expired animation data. + if (!isValidAnimation) { + clearElementAnimationState(element); + } + + return; + } + + // this combined multiple class to addClass / removeClass into a setClass event + // so long as a structural event did not take over the animation + event = !animationDetails.structural && hasAnimationClasses(animationDetails, true) + ? 'setClass' + : animationDetails.event; + + markElementAnimationState(element, RUNNING_STATE); + var realRunner = $$animation(element, event, animationDetails.options); + + // this will update the runner's flow-control events based on + // the `realRunner` object. + runner.setHost(realRunner); + notifyProgress(runner, event, 'start', {}); + + realRunner.done(function(status) { + close(!status); + var animationDetails = activeAnimationsLookup.get(node); + if (animationDetails && animationDetails.counter === counter) { + clearElementAnimationState(getDomNode(element)); + } + notifyProgress(runner, event, 'close', {}); + }); + }); + + return runner; + + function notifyProgress(runner, event, phase, data) { + runInNextPostDigestOrNow(function() { + var callbacks = findCallbacks(parent, element, event); + if (callbacks.length) { + // do not optimize this call here to RAF because + // we don't know how heavy the callback code here will + // be and if this code is buffered then this can + // lead to a performance regression. + $$rAF(function() { + forEach(callbacks, function(callback) { + callback(element, phase, data); + }); + cleanupEventListeners(phase, element); + }); + } else { + cleanupEventListeners(phase, element); + } + }); + runner.progress(event, phase, data); + } + + function close(reject) { // jshint ignore:line + clearGeneratedClasses(element, options); + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + options.domOperation(); + runner.complete(!reject); + } + } + + function closeChildAnimations(element) { + var node = getDomNode(element); + var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']'); + forEach(children, function(child) { + var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME)); + var animationDetails = activeAnimationsLookup.get(child); + if (animationDetails) { + switch (state) { + case RUNNING_STATE: + animationDetails.runner.end(); + /* falls through */ + case PRE_DIGEST_STATE: + activeAnimationsLookup.remove(child); + break; + } + } + }); + } + + function clearElementAnimationState(element) { + var node = getDomNode(element); + node.removeAttribute(NG_ANIMATE_ATTR_NAME); + activeAnimationsLookup.remove(node); + } + + function isMatchingElement(nodeOrElmA, nodeOrElmB) { + return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB); + } + + /** + * This fn returns false if any of the following is true: + * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed + * b) a parent element has an ongoing structural animation, and animateChildren is false + * c) the element is not a child of the body + * d) the element is not a child of the $rootElement + */ + function areAnimationsAllowed(element, parentElement, event) { + var bodyElement = jqLite($document[0].body); + var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML'; + var rootElementDetected = isMatchingElement(element, $rootElement); + var parentAnimationDetected = false; + var animateChildren; + var elementDisabled = disabledElementsLookup.get(getDomNode(element)); + + var parentHost = jqLite.data(element[0], NG_ANIMATE_PIN_DATA); + if (parentHost) { + parentElement = parentHost; + } + + parentElement = getDomNode(parentElement); + + while (parentElement) { + if (!rootElementDetected) { + // angular doesn't want to attempt to animate elements outside of the application + // therefore we need to ensure that the rootElement is an ancestor of the current element + rootElementDetected = isMatchingElement(parentElement, $rootElement); + } + + if (parentElement.nodeType !== ELEMENT_NODE) { + // no point in inspecting the #document element + break; + } + + var details = activeAnimationsLookup.get(parentElement) || {}; + // either an enter, leave or move animation will commence + // therefore we can't allow any animations to take place + // but if a parent animation is class-based then that's ok + if (!parentAnimationDetected) { + var parentElementDisabled = disabledElementsLookup.get(parentElement); + + if (parentElementDisabled === true && elementDisabled !== false) { + // disable animations if the user hasn't explicitly enabled animations on the + // current element + elementDisabled = true; + // element is disabled via parent element, no need to check anything else + break; + } else if (parentElementDisabled === false) { + elementDisabled = false; + } + parentAnimationDetected = details.structural; + } + + if (isUndefined(animateChildren) || animateChildren === true) { + var value = jqLite.data(parentElement, NG_ANIMATE_CHILDREN_DATA); + if (isDefined(value)) { + animateChildren = value; + } + } + + // there is no need to continue traversing at this point + if (parentAnimationDetected && animateChildren === false) break; + + if (!bodyElementDetected) { + // we also need to ensure that the element is or will be a part of the body element + // otherwise it is pointless to even issue an animation to be rendered + bodyElementDetected = isMatchingElement(parentElement, bodyElement); + } + + if (bodyElementDetected && rootElementDetected) { + // If both body and root have been found, any other checks are pointless, + // as no animation data should live outside the application + break; + } + + if (!rootElementDetected) { + // If no rootElement is detected, check if the parentElement is pinned to another element + parentHost = jqLite.data(parentElement, NG_ANIMATE_PIN_DATA); + if (parentHost) { + // The pin target element becomes the next parent element + parentElement = getDomNode(parentHost); + continue; + } + } + + parentElement = parentElement.parentNode; + } + + var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true; + return allowAnimation && rootElementDetected && bodyElementDetected; + } + + function markElementAnimationState(element, state, details) { + details = details || {}; + details.state = state; + + var node = getDomNode(element); + node.setAttribute(NG_ANIMATE_ATTR_NAME, state); + + var oldValue = activeAnimationsLookup.get(node); + var newValue = oldValue + ? extend(oldValue, details) + : details; + activeAnimationsLookup.put(node, newValue); + } + }]; +}]; + +var $$AnimationProvider = ['$animateProvider', function($animateProvider) { + var NG_ANIMATE_REF_ATTR = 'ng-animate-ref'; + + var drivers = this.drivers = []; + + var RUNNER_STORAGE_KEY = '$$animationRunner'; + + function setRunner(element, runner) { + element.data(RUNNER_STORAGE_KEY, runner); + } + + function removeRunner(element) { + element.removeData(RUNNER_STORAGE_KEY); + } + + function getRunner(element) { + return element.data(RUNNER_STORAGE_KEY); + } + + this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler', + function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) { + + var animationQueue = []; + var applyAnimationClasses = applyAnimationClassesFactory($$jqLite); + + function sortAnimations(animations) { + var tree = { children: [] }; + var i, lookup = new $$HashMap(); + + // this is done first beforehand so that the hashmap + // is filled with a list of the elements that will be animated + for (i = 0; i < animations.length; i++) { + var animation = animations[i]; + lookup.put(animation.domNode, animations[i] = { + domNode: animation.domNode, + fn: animation.fn, + children: [] + }); + } + + for (i = 0; i < animations.length; i++) { + processNode(animations[i]); + } + + return flatten(tree); + + function processNode(entry) { + if (entry.processed) return entry; + entry.processed = true; + + var elementNode = entry.domNode; + var parentNode = elementNode.parentNode; + lookup.put(elementNode, entry); + + var parentEntry; + while (parentNode) { + parentEntry = lookup.get(parentNode); + if (parentEntry) { + if (!parentEntry.processed) { + parentEntry = processNode(parentEntry); + } + break; + } + parentNode = parentNode.parentNode; + } + + (parentEntry || tree).children.push(entry); + return entry; + } + + function flatten(tree) { + var result = []; + var queue = []; + var i; + + for (i = 0; i < tree.children.length; i++) { + queue.push(tree.children[i]); + } + + var remainingLevelEntries = queue.length; + var nextLevelEntries = 0; + var row = []; + + for (i = 0; i < queue.length; i++) { + var entry = queue[i]; + if (remainingLevelEntries <= 0) { + remainingLevelEntries = nextLevelEntries; + nextLevelEntries = 0; + result.push(row); + row = []; + } + row.push(entry.fn); + entry.children.forEach(function(childEntry) { + nextLevelEntries++; + queue.push(childEntry); + }); + remainingLevelEntries--; + } + + if (row.length) { + result.push(row); + } + + return result; + } + } + + // TODO(matsko): document the signature in a better way + return function(element, event, options) { + options = prepareAnimationOptions(options); + var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0; + + // there is no animation at the current moment, however + // these runner methods will get later updated with the + // methods leading into the driver's end/cancel methods + // for now they just stop the animation from starting + var runner = new $$AnimateRunner({ + end: function() { close(); }, + cancel: function() { close(true); } + }); + + if (!drivers.length) { + close(); + return runner; + } + + setRunner(element, runner); + + var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass)); + var tempClasses = options.tempClasses; + if (tempClasses) { + classes += ' ' + tempClasses; + options.tempClasses = null; + } + + var prepareClassName; + if (isStructural) { + prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX; + $$jqLite.addClass(element, prepareClassName); + } + + animationQueue.push({ + // this data is used by the postDigest code and passed into + // the driver step function + element: element, + classes: classes, + event: event, + structural: isStructural, + options: options, + beforeStart: beforeStart, + close: close + }); + + element.on('$destroy', handleDestroyedElement); + + // we only want there to be one function called within the post digest + // block. This way we can group animations for all the animations that + // were apart of the same postDigest flush call. + if (animationQueue.length > 1) return runner; + + $rootScope.$$postDigest(function() { + var animations = []; + forEach(animationQueue, function(entry) { + // the element was destroyed early on which removed the runner + // form its storage. This means we can't animate this element + // at all and it already has been closed due to destruction. + if (getRunner(entry.element)) { + animations.push(entry); + } else { + entry.close(); + } + }); + + // now any future animations will be in another postDigest + animationQueue.length = 0; + + var groupedAnimations = groupAnimations(animations); + var toBeSortedAnimations = []; + + forEach(groupedAnimations, function(animationEntry) { + toBeSortedAnimations.push({ + domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element), + fn: function triggerAnimationStart() { + // it's important that we apply the `ng-animate` CSS class and the + // temporary classes before we do any driver invoking since these + // CSS classes may be required for proper CSS detection. + animationEntry.beforeStart(); + + var startAnimationFn, closeFn = animationEntry.close; + + // in the event that the element was removed before the digest runs or + // during the RAF sequencing then we should not trigger the animation. + var targetElement = animationEntry.anchors + ? (animationEntry.from.element || animationEntry.to.element) + : animationEntry.element; + + if (getRunner(targetElement)) { + var operation = invokeFirstDriver(animationEntry); + if (operation) { + startAnimationFn = operation.start; + } + } + + if (!startAnimationFn) { + closeFn(); + } else { + var animationRunner = startAnimationFn(); + animationRunner.done(function(status) { + closeFn(!status); + }); + updateAnimationRunners(animationEntry, animationRunner); + } + } + }); + }); + + // we need to sort each of the animations in order of parent to child + // relationships. This ensures that the child classes are applied at the + // right time. + $$rAFScheduler(sortAnimations(toBeSortedAnimations)); + }); + + return runner; + + // TODO(matsko): change to reference nodes + function getAnchorNodes(node) { + var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']'; + var items = node.hasAttribute(NG_ANIMATE_REF_ATTR) + ? [node] + : node.querySelectorAll(SELECTOR); + var anchors = []; + forEach(items, function(node) { + var attr = node.getAttribute(NG_ANIMATE_REF_ATTR); + if (attr && attr.length) { + anchors.push(node); + } + }); + return anchors; + } + + function groupAnimations(animations) { + var preparedAnimations = []; + var refLookup = {}; + forEach(animations, function(animation, index) { + var element = animation.element; + var node = getDomNode(element); + var event = animation.event; + var enterOrMove = ['enter', 'move'].indexOf(event) >= 0; + var anchorNodes = animation.structural ? getAnchorNodes(node) : []; + + if (anchorNodes.length) { + var direction = enterOrMove ? 'to' : 'from'; + + forEach(anchorNodes, function(anchor) { + var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR); + refLookup[key] = refLookup[key] || {}; + refLookup[key][direction] = { + animationID: index, + element: jqLite(anchor) + }; + }); + } else { + preparedAnimations.push(animation); + } + }); + + var usedIndicesLookup = {}; + var anchorGroups = {}; + forEach(refLookup, function(operations, key) { + var from = operations.from; + var to = operations.to; + + if (!from || !to) { + // only one of these is set therefore we can't have an + // anchor animation since all three pieces are required + var index = from ? from.animationID : to.animationID; + var indexKey = index.toString(); + if (!usedIndicesLookup[indexKey]) { + usedIndicesLookup[indexKey] = true; + preparedAnimations.push(animations[index]); + } + return; + } + + var fromAnimation = animations[from.animationID]; + var toAnimation = animations[to.animationID]; + var lookupKey = from.animationID.toString(); + if (!anchorGroups[lookupKey]) { + var group = anchorGroups[lookupKey] = { + structural: true, + beforeStart: function() { + fromAnimation.beforeStart(); + toAnimation.beforeStart(); + }, + close: function() { + fromAnimation.close(); + toAnimation.close(); + }, + classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes), + from: fromAnimation, + to: toAnimation, + anchors: [] // TODO(matsko): change to reference nodes + }; + + // the anchor animations require that the from and to elements both have at least + // one shared CSS class which effectively marries the two elements together to use + // the same animation driver and to properly sequence the anchor animation. + if (group.classes.length) { + preparedAnimations.push(group); + } else { + preparedAnimations.push(fromAnimation); + preparedAnimations.push(toAnimation); + } + } + + anchorGroups[lookupKey].anchors.push({ + 'out': from.element, 'in': to.element + }); + }); + + return preparedAnimations; + } + + function cssClassesIntersection(a,b) { + a = a.split(' '); + b = b.split(' '); + var matches = []; + + for (var i = 0; i < a.length; i++) { + var aa = a[i]; + if (aa.substring(0,3) === 'ng-') continue; + + for (var j = 0; j < b.length; j++) { + if (aa === b[j]) { + matches.push(aa); + break; + } + } + } + + return matches.join(' '); + } + + function invokeFirstDriver(animationDetails) { + // we loop in reverse order since the more general drivers (like CSS and JS) + // may attempt more elements, but custom drivers are more particular + for (var i = drivers.length - 1; i >= 0; i--) { + var driverName = drivers[i]; + var factory = $injector.get(driverName); + var driver = factory(animationDetails); + if (driver) { + return driver; + } + } + } + + function beforeStart() { + element.addClass(NG_ANIMATE_CLASSNAME); + if (tempClasses) { + $$jqLite.addClass(element, tempClasses); + } + if (prepareClassName) { + $$jqLite.removeClass(element, prepareClassName); + prepareClassName = null; + } + } + + function updateAnimationRunners(animation, newRunner) { + if (animation.from && animation.to) { + update(animation.from.element); + update(animation.to.element); + } else { + update(animation.element); + } + + function update(element) { + var runner = getRunner(element); + if (runner) runner.setHost(newRunner); + } + } + + function handleDestroyedElement() { + var runner = getRunner(element); + if (runner && (event !== 'leave' || !options.$$domOperationFired)) { + runner.end(); + } + } + + function close(rejected) { // jshint ignore:line + element.off('$destroy', handleDestroyedElement); + removeRunner(element); + + applyAnimationClasses(element, options); + applyAnimationStyles(element, options); + options.domOperation(); + + if (tempClasses) { + $$jqLite.removeClass(element, tempClasses); + } + + element.removeClass(NG_ANIMATE_CLASSNAME); + runner.complete(!rejected); + } + }; + }]; +}]; + +/** + * @ngdoc directive + * @name ngAnimateSwap + * @restrict A + * @scope + * + * @description + * + * ngAnimateSwap is a animation-oriented directive that allows for the container to + * be removed and entered in whenever the associated expression changes. A + * common usecase for this directive is a rotating banner or slider component which + * contains one image being present at a time. When the active image changes + * then the old image will perform a `leave` animation and the new element + * will be inserted via an `enter` animation. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|--------------------------------------| + * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM | + * | {@link ng.$animate#leave leave} | when the old element is removed from the DOM | + * + * @example + * + * + *
    + *
    + * {{ number }} + *
    + *
    + *
    + * + * angular.module('ngAnimateSwapExample', ['ngAnimate']) + * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) { + * $scope.number = 0; + * $interval(function() { + * $scope.number++; + * }, 1000); + * + * var colors = ['red','blue','green','yellow','orange']; + * $scope.colorClass = function(number) { + * return colors[number % colors.length]; + * }; + * }]); + * + * + * .container { + * height:250px; + * width:250px; + * position:relative; + * overflow:hidden; + * border:2px solid black; + * } + * .container .cell { + * font-size:150px; + * text-align:center; + * line-height:250px; + * position:absolute; + * top:0; + * left:0; + * right:0; + * border-bottom:2px solid black; + * } + * .swap-animation.ng-enter, .swap-animation.ng-leave { + * transition:0.5s linear all; + * } + * .swap-animation.ng-enter { + * top:-250px; + * } + * .swap-animation.ng-enter-active { + * top:0px; + * } + * .swap-animation.ng-leave { + * top:0px; + * } + * .swap-animation.ng-leave-active { + * top:250px; + * } + * .red { background:red; } + * .green { background:green; } + * .blue { background:blue; } + * .yellow { background:yellow; } + * .orange { background:orange; } + * + *
    + */ +var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) { + return { + restrict: 'A', + transclude: 'element', + terminal: true, + priority: 600, // we use 600 here to ensure that the directive is caught before others + link: function(scope, $element, attrs, ctrl, $transclude) { + var previousElement, previousScope; + scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) { + if (previousElement) { + $animate.leave(previousElement); + } + if (previousScope) { + previousScope.$destroy(); + previousScope = null; + } + if (value || value === 0) { + previousScope = scope.$new(); + $transclude(previousScope, function(element) { + previousElement = element; + $animate.enter(element, null, $element); + }); + } + }); + } + }; +}]; + +/** + * @ngdoc module + * @name ngAnimate + * @description + * + * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via + * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app. + * + *
    + * + * # Usage + * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based + * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For + * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within + * the HTML element that the animation will be triggered on. + * + * ## Directive Support + * The following directives are "animation aware": + * + * | Directive | Supported Animations | + * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------| + * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move | + * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave | + * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave | + * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave | + * | {@link ng.directive:ngIf#animations ngIf} | enter and leave | + * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) | + * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) | + * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | + * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) | + * | {@link module:ngMessages#animations ngMessage} | enter and leave | + * + * (More information can be found by visiting each the documentation associated with each directive.) + * + * ## CSS-based Animations + * + * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML + * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation. + * + * The example below shows how an `enter` animation can be made possible on an element using `ng-if`: + * + * ```html + *
    + * Fade me in out + *
    + * + * + * ``` + * + * Notice the CSS class **fade**? We can now create the CSS transition code that references this class: + * + * ```css + * /* The starting CSS styles for the enter animation */ + * .fade.ng-enter { + * transition:0.5s linear all; + * opacity:0; + * } + * + * /* The finishing CSS styles for the enter animation */ + * .fade.ng-enter.ng-enter-active { + * opacity:1; + * } + * ``` + * + * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two + * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition + * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards. + * + * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions: + * + * ```css + * /* now the element will fade out before it is removed from the DOM */ + * .fade.ng-leave { + * transition:0.5s linear all; + * opacity:1; + * } + * .fade.ng-leave.ng-leave-active { + * opacity:0; + * } + * ``` + * + * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class: + * + * ```css + * /* there is no need to define anything inside of the destination + * CSS class since the keyframe will take charge of the animation */ + * .fade.ng-leave { + * animation: my_fade_animation 0.5s linear; + * -webkit-animation: my_fade_animation 0.5s linear; + * } + * + * @keyframes my_fade_animation { + * from { opacity:1; } + * to { opacity:0; } + * } + * + * @-webkit-keyframes my_fade_animation { + * from { opacity:1; } + * to { opacity:0; } + * } + * ``` + * + * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element. + * + * ### CSS Class-based Animations + * + * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different + * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added + * and removed. + * + * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class: + * + * ```html + *
    + * Show and hide me + *
    + * + * + * + * ``` + * + * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since + * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest. + * + * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation + * with CSS styles. + * + * ```html + *
    + * Highlight this box + *
    + * + * + * + * ``` + * + * We can also make use of CSS keyframes by placing them within the CSS classes. + * + * + * ### CSS Staggering Animations + * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a + * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be + * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for + * the animation. The style property expected within the stagger class can either be a **transition-delay** or an + * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). + * + * ```css + * .my-animation.ng-enter { + * /* standard transition code */ + * transition: 1s linear all; + * opacity:0; + * } + * .my-animation.ng-enter-stagger { + * /* this will have a 100ms delay between each successive leave animation */ + * transition-delay: 0.1s; + * + * /* As of 1.4.4, this must always be set: it signals ngAnimate + * to not accidentally inherit a delay property from another CSS class */ + * transition-duration: 0s; + * } + * .my-animation.ng-enter.ng-enter-active { + * /* standard transition styles */ + * opacity:1; + * } + * ``` + * + * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations + * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this + * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation + * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired. + * + * The following code will issue the **ng-leave-stagger** event on the element provided: + * + * ```js + * var kids = parent.children(); + * + * $animate.leave(kids[0]); //stagger index=0 + * $animate.leave(kids[1]); //stagger index=1 + * $animate.leave(kids[2]); //stagger index=2 + * $animate.leave(kids[3]); //stagger index=3 + * $animate.leave(kids[4]); //stagger index=4 + * + * window.requestAnimationFrame(function() { + * //stagger has reset itself + * $animate.leave(kids[5]); //stagger index=0 + * $animate.leave(kids[6]); //stagger index=1 + * + * $scope.$digest(); + * }); + * ``` + * + * Stagger animations are currently only supported within CSS-defined animations. + * + * ### The `ng-animate` CSS class + * + * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation. + * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations). + * + * Therefore, animations can be applied to an element using this temporary class directly via CSS. + * + * ```css + * .zipper.ng-animate { + * transition:0.5s linear all; + * } + * .zipper.ng-enter { + * opacity:0; + * } + * .zipper.ng-enter.ng-enter-active { + * opacity:1; + * } + * .zipper.ng-leave { + * opacity:1; + * } + * .zipper.ng-leave.ng-leave-active { + * opacity:0; + * } + * ``` + * + * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove + * the CSS class once an animation has completed.) + * + * + * ### The `ng-[event]-prepare` class + * + * This is a special class that can be used to prevent unwanted flickering / flash of content before + * the actual animation starts. The class is added as soon as an animation is initialized, but removed + * before the actual animation starts (after waiting for a $digest). + * It is also only added for *structural* animations (`enter`, `move`, and `leave`). + * + * In practice, flickering can appear when nesting elements with structural animations such as `ngIf` + * into elements that have class-based animations such as `ngClass`. + * + * ```html + *
    + *
    + *
    + *
    + *
    + * ``` + * + * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating. + * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts: + * + * ```css + * .message.ng-enter-prepare { + * opacity: 0; + * } + * + * ``` + * + * ## JavaScript-based Animations + * + * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared + * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the + * `module.animation()` module function we can register the animation. + * + * Let's see an example of a enter/leave animation using `ngRepeat`: + * + * ```html + *
    + * {{ item }} + *
    + * ``` + * + * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`: + * + * ```js + * myModule.animation('.slide', [function() { + * return { + * // make note that other events (like addClass/removeClass) + * // have different function input parameters + * enter: function(element, doneFn) { + * jQuery(element).fadeIn(1000, doneFn); + * + * // remember to call doneFn so that angular + * // knows that the animation has concluded + * }, + * + * move: function(element, doneFn) { + * jQuery(element).fadeIn(1000, doneFn); + * }, + * + * leave: function(element, doneFn) { + * jQuery(element).fadeOut(1000, doneFn); + * } + * } + * }]); + * ``` + * + * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as + * greensock.js and velocity.js. + * + * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define + * our animations inside of the same registered animation, however, the function input arguments are a bit different: + * + * ```html + *
    + * this box is moody + *
    + * + * + * + * ``` + * + * ```js + * myModule.animation('.colorful', [function() { + * return { + * addClass: function(element, className, doneFn) { + * // do some cool animation and call the doneFn + * }, + * removeClass: function(element, className, doneFn) { + * // do some cool animation and call the doneFn + * }, + * setClass: function(element, addedClass, removedClass, doneFn) { + * // do some cool animation and call the doneFn + * } + * } + * }]); + * ``` + * + * ## CSS + JS Animations Together + * + * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular, + * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking + * charge of the animation**: + * + * ```html + *
    + * Slide in and out + *
    + * ``` + * + * ```js + * myModule.animation('.slide', [function() { + * return { + * enter: function(element, doneFn) { + * jQuery(element).slideIn(1000, doneFn); + * } + * } + * }]); + * ``` + * + * ```css + * .slide.ng-enter { + * transition:0.5s linear all; + * transform:translateY(-100px); + * } + * .slide.ng-enter.ng-enter-active { + * transform:translateY(0); + * } + * ``` + * + * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the + * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from + * our own JS-based animation code: + * + * ```js + * myModule.animation('.slide', ['$animateCss', function($animateCss) { + * return { + * enter: function(element) { +* // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`. + * return $animateCss(element, { + * event: 'enter', + * structural: true + * }); + * } + * } + * }]); + * ``` + * + * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework. + * + * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or + * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that + * data into `$animateCss` directly: + * + * ```js + * myModule.animation('.slide', ['$animateCss', function($animateCss) { + * return { + * enter: function(element) { + * return $animateCss(element, { + * event: 'enter', + * structural: true, + * addClass: 'maroon-setting', + * from: { height:0 }, + * to: { height: 200 } + * }); + * } + * } + * }]); + * ``` + * + * Now we can fill in the rest via our transition CSS code: + * + * ```css + * /* the transition tells ngAnimate to make the animation happen */ + * .slide.ng-enter { transition:0.5s linear all; } + * + * /* this extra CSS class will be absorbed into the transition + * since the $animateCss code is adding the class */ + * .maroon-setting { background:red; } + * ``` + * + * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over. + * + * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}. + * + * ## Animation Anchoring (via `ng-animate-ref`) + * + * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between + * structural areas of an application (like views) by pairing up elements using an attribute + * called `ng-animate-ref`. + * + * Let's say for example we have two views that are managed by `ng-view` and we want to show + * that there is a relationship between two components situated in within these views. By using the + * `ng-animate-ref` attribute we can identify that the two components are paired together and we + * can then attach an animation, which is triggered when the view changes. + * + * Say for example we have the following template code: + * + * ```html + * + *
    + *
    + * + * + * + * + * + * + * + * + * ``` + * + * Now, when the view changes (once the link is clicked), ngAnimate will examine the + * HTML contents to see if there is a match reference between any components in the view + * that is leaving and the view that is entering. It will scan both the view which is being + * removed (leave) and inserted (enter) to see if there are any paired DOM elements that + * contain a matching ref value. + * + * The two images match since they share the same ref value. ngAnimate will now create a + * transport element (which is a clone of the first image element) and it will then attempt + * to animate to the position of the second image element in the next view. For the animation to + * work a special CSS class called `ng-anchor` will be added to the transported element. + * + * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then + * ngAnimate will handle the entire transition for us as well as the addition and removal of + * any changes of CSS classes between the elements: + * + * ```css + * .banner.ng-anchor { + * /* this animation will last for 1 second since there are + * two phases to the animation (an `in` and an `out` phase) */ + * transition:0.5s linear all; + * } + * ``` + * + * We also **must** include animations for the views that are being entered and removed + * (otherwise anchoring wouldn't be possible since the new view would be inserted right away). + * + * ```css + * .view-animation.ng-enter, .view-animation.ng-leave { + * transition:0.5s linear all; + * position:fixed; + * left:0; + * top:0; + * width:100%; + * } + * .view-animation.ng-enter { + * transform:translateX(100%); + * } + * .view-animation.ng-leave, + * .view-animation.ng-enter.ng-enter-active { + * transform:translateX(0%); + * } + * .view-animation.ng-leave.ng-leave-active { + * transform:translateX(-100%); + * } + * ``` + * + * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur: + * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away + * from its origin. Once that animation is over then the `in` stage occurs which animates the + * element to its destination. The reason why there are two animations is to give enough time + * for the enter animation on the new element to be ready. + * + * The example above sets up a transition for both the in and out phases, but we can also target the out or + * in phases directly via `ng-anchor-out` and `ng-anchor-in`. + * + * ```css + * .banner.ng-anchor-out { + * transition: 0.5s linear all; + * + * /* the scale will be applied during the out animation, + * but will be animated away when the in animation runs */ + * transform: scale(1.2); + * } + * + * .banner.ng-anchor-in { + * transition: 1s linear all; + * } + * ``` + * + * + * + * + * ### Anchoring Demo + * + + + Home +
    +
    +
    +
    +
    + + angular.module('anchoringExample', ['ngAnimate', 'ngRoute']) + .config(['$routeProvider', function($routeProvider) { + $routeProvider.when('/', { + templateUrl: 'home.html', + controller: 'HomeController as home' + }); + $routeProvider.when('/profile/:id', { + templateUrl: 'profile.html', + controller: 'ProfileController as profile' + }); + }]) + .run(['$rootScope', function($rootScope) { + $rootScope.records = [ + { id:1, title: "Miss Beulah Roob" }, + { id:2, title: "Trent Morissette" }, + { id:3, title: "Miss Ava Pouros" }, + { id:4, title: "Rod Pouros" }, + { id:5, title: "Abdul Rice" }, + { id:6, title: "Laurie Rutherford Sr." }, + { id:7, title: "Nakia McLaughlin" }, + { id:8, title: "Jordon Blanda DVM" }, + { id:9, title: "Rhoda Hand" }, + { id:10, title: "Alexandrea Sauer" } + ]; + }]) + .controller('HomeController', [function() { + //empty + }]) + .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) { + var index = parseInt($routeParams.id, 10); + var record = $rootScope.records[index - 1]; + + this.title = record.title; + this.id = record.id; + }]); + + +

    Welcome to the home page

    +

    Please click on an element

    + + {{ record.title }} + +
    + +
    + {{ profile.title }} +
    +
    + + .record { + display:block; + font-size:20px; + } + .profile { + background:black; + color:white; + font-size:100px; + } + .view-container { + position:relative; + } + .view-container > .view.ng-animate { + position:absolute; + top:0; + left:0; + width:100%; + min-height:500px; + } + .view.ng-enter, .view.ng-leave, + .record.ng-anchor { + transition:0.5s linear all; + } + .view.ng-enter { + transform:translateX(100%); + } + .view.ng-enter.ng-enter-active, .view.ng-leave { + transform:translateX(0%); + } + .view.ng-leave.ng-leave-active { + transform:translateX(-100%); + } + .record.ng-anchor-out { + background:red; + } + +
    + * + * ### How is the element transported? + * + * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting + * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element + * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The + * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match + * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied + * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class + * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element + * will become visible since the shim class will be removed. + * + * ### How is the morphing handled? + * + * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out + * what CSS classes differ between the starting element and the destination element. These different CSS classes + * will be added/removed on the anchor element and a transition will be applied (the transition that is provided + * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will + * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that + * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since + * the cloned element is placed inside of root element which is likely close to the body element). + * + * Note that if the root element is on the `` element then the cloned node will be placed inside of body. + * + * + * ## Using $animate in your directive code + * + * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application? + * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's + * imagine we have a greeting box that shows and hides itself when the data changes + * + * ```html + * Hi there + * ``` + * + * ```js + * ngModule.directive('greetingBox', ['$animate', function($animate) { + * return function(scope, element, attrs) { + * attrs.$observe('active', function(value) { + * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on'); + * }); + * }); + * }]); + * ``` + * + * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element + * in our HTML code then we can trigger a CSS or JS animation to happen. + * + * ```css + * /* normally we would create a CSS class to reference on the element */ + * greeting-box.on { transition:0.5s linear all; background:green; color:white; } + * ``` + * + * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's + * possible be sure to visit the {@link ng.$animate $animate service API page}. + * + * + * ## Callbacks and Promises + * + * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger + * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has + * ended by chaining onto the returned promise that animation method returns. + * + * ```js + * // somewhere within the depths of the directive + * $animate.enter(element, parent).then(function() { + * //the animation has completed + * }); + * ``` + * + * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case + * anymore.) + * + * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering + * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view + * routing controller to hook into that: + * + * ```js + * ngModule.controller('HomePageController', ['$animate', function($animate) { + * $animate.on('enter', ngViewElement, function(element) { + * // the animation for this route has completed + * }]); + * }]) + * ``` + * + * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.) + */ + +var copy; +var extend; +var forEach; +var isArray; +var isDefined; +var isElement; +var isFunction; +var isObject; +var isString; +var isUndefined; +var jqLite; +var noop; + +/** + * @ngdoc service + * @name $animate + * @kind object + * + * @description + * The ngAnimate `$animate` service documentation is the same for the core `$animate` service. + * + * Click here {@link ng.$animate to learn more about animations with `$animate`}. + */ +angular.module('ngAnimate', [], function initAngularHelpers() { + // Access helpers from angular core. + // Do it inside a `config` block to ensure `window.angular` is available. + noop = angular.noop; + copy = angular.copy; + extend = angular.extend; + jqLite = angular.element; + forEach = angular.forEach; + isArray = angular.isArray; + isString = angular.isString; + isObject = angular.isObject; + isUndefined = angular.isUndefined; + isDefined = angular.isDefined; + isFunction = angular.isFunction; + isElement = angular.isElement; +}) + .directive('ngAnimateSwap', ngAnimateSwapDirective) + + .directive('ngAnimateChildren', $$AnimateChildrenDirective) + .factory('$$rAFScheduler', $$rAFSchedulerFactory) + + .provider('$$animateQueue', $$AnimateQueueProvider) + .provider('$$animation', $$AnimationProvider) + + .provider('$animateCss', $AnimateCssProvider) + .provider('$$animateCssDriver', $$AnimateCssDriverProvider) + + .provider('$$animateJs', $$AnimateJsProvider) + .provider('$$animateJsDriver', $$AnimateJsDriverProvider); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-animate.min.js b/src/main/resources/static/module/angular/angular-animate.min.js new file mode 100644 index 0000000..b4087ed --- /dev/null +++ b/src/main/resources/static/module/angular/angular-animate.min.js @@ -0,0 +1,57 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(R,B){'use strict';function Da(a,b,c){if(!a)throw Ma("areq",b||"?",c||"required");return a}function Ea(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;Y(a)&&(a=a.join(" "));Y(b)&&(b=b.join(" "));return a+" "+b}function Na(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function Z(a,b,c){var d="";a=Y(a)?a:a&&G(a)&&a.length?a.split(/\s+/):[];s(a,function(a,l){a&&0=a&&(a=e,e=0,b.push(k),k=[]);k.push(g.fn);g.children.forEach(function(a){e++;c.push(a)});a--}k.length&&b.push(k);return b}(c)}var u=[],C=V(a);return function(n,Q,t){function H(a){a= +a.hasAttribute("ng-animate-ref")?[a]:a.querySelectorAll("[ng-animate-ref]");var b=[];s(a,function(a){var c=a.getAttribute("ng-animate-ref");c&&c.length&&b.push(a)});return b}function T(a){var b=[],c={};s(a,function(a,d){var h=y(a.element),e=0<=["enter","move"].indexOf(a.event),h=a.structural?H(h):[];if(h.length){var k=e?"to":"from";s(h,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]||{};c[b][k]={animationID:d,element:F(a)}})}else b.push(a)});var d={},e={};s(c,function(c,k){var r=c.from, +p=c.to;if(r&&p){var z=a[r.animationID],g=a[p.animationID],A=r.animationID.toString();if(!e[A]){var n=e[A]={structural:!0,beforeStart:function(){z.beforeStart();g.beforeStart()},close:function(){z.close();g.close()},classes:O(z.classes,g.classes),from:z,to:g,anchors:[]};n.classes.length?b.push(n):(b.push(z),b.push(g))}e[A].anchors.push({out:r.element,"in":p.element})}else r=r?r.animationID:p.animationID,p=r.toString(),d[p]||(d[p]=!0,b.push(a[r]))});return b}function O(a,b){a=a.split(" ");b=b.split(" "); +for(var c=[],d=0;d=R&&b>=m&&(F=!0,k())}function N(){function b(){if(!w){M(!1);s(x,function(a){h.style[a[0]]=a[1]});T(a,f);e.addClass(a,ea);if(q.recalculateTimingStyles){na= +h.className+" "+ga;ia=B(h,na);D=H(h,na,ia);ca=D.maxDelay;J=Math.max(ca,0);m=D.maxDuration;if(0===m){k();return}q.hasTransitions=0l.expectedEndTime)?n.cancel(l.timer):g.push(k)}N&&(p=n(c,p,!1),g[0]={timer:p,expectedEndTime:d},g.push(k),a.data("$$animateCss",g));if(fa.length)a.on(fa.join(" "),z);f.to&&(f.cleanupStyles&&Ka(A,h,Object.keys(f.to)),Ga(a,f))}}function c(){var b=a.data("$$animateCss");if(b){for(var d=1;dARIA](http://www.w3.org/TR/wai-aria/) + * attributes that convey state or semantic information about the application for users + * of assistive technologies, such as screen readers. + * + *
    + * + * ## Usage + * + * For ngAria to do its magic, simply include the module `ngAria` as a dependency. The following + * directives are supported: + * `ngModel`, `ngChecked`, `ngReadonly`, `ngRequired`, `ngValue`, `ngDisabled`, `ngShow`, `ngHide`, `ngClick`, + * `ngDblClick`, and `ngMessages`. + * + * Below is a more detailed breakdown of the attributes handled by ngAria: + * + * | Directive | Supported Attributes | + * |---------------------------------------------|----------------------------------------------------------------------------------------| + * | {@link ng.directive:ngModel ngModel} | aria-checked, aria-valuemin, aria-valuemax, aria-valuenow, aria-invalid, aria-required, input roles | + * | {@link ng.directive:ngDisabled ngDisabled} | aria-disabled | + * | {@link ng.directive:ngRequired ngRequired} | aria-required + * | {@link ng.directive:ngChecked ngChecked} | aria-checked + * | {@link ng.directive:ngReadonly ngReadonly} | aria-readonly | + * | {@link ng.directive:ngValue ngValue} | aria-checked | + * | {@link ng.directive:ngShow ngShow} | aria-hidden | + * | {@link ng.directive:ngHide ngHide} | aria-hidden | + * | {@link ng.directive:ngDblclick ngDblclick} | tabindex | + * | {@link module:ngMessages ngMessages} | aria-live | + * | {@link ng.directive:ngClick ngClick} | tabindex, keypress event, button role | + * + * Find out more information about each directive by reading the + * {@link guide/accessibility ngAria Developer Guide}. + * + * ## Example + * Using ngDisabled with ngAria: + * ```html + * + * ``` + * Becomes: + * ```html + * + * ``` + * + * ## Disabling Attributes + * It's possible to disable individual attributes added by ngAria with the + * {@link ngAria.$ariaProvider#config config} method. For more details, see the + * {@link guide/accessibility Developer Guide}. + */ + /* global -ngAriaModule */ +var ngAriaModule = angular.module('ngAria', ['ng']). + provider('$aria', $AriaProvider); + +/** +* Internal Utilities +*/ +var nodeBlackList = ['BUTTON', 'A', 'INPUT', 'TEXTAREA', 'SELECT', 'DETAILS', 'SUMMARY']; + +var isNodeOneOf = function(elem, nodeTypeArray) { + if (nodeTypeArray.indexOf(elem[0].nodeName) !== -1) { + return true; + } +}; +/** + * @ngdoc provider + * @name $ariaProvider + * + * @description + * + * Used for configuring the ARIA attributes injected and managed by ngAria. + * + * ```js + * angular.module('myApp', ['ngAria'], function config($ariaProvider) { + * $ariaProvider.config({ + * ariaValue: true, + * tabindex: false + * }); + * }); + *``` + * + * ## Dependencies + * Requires the {@link ngAria} module to be installed. + * + */ +function $AriaProvider() { + var config = { + ariaHidden: true, + ariaChecked: true, + ariaReadonly: true, + ariaDisabled: true, + ariaRequired: true, + ariaInvalid: true, + ariaValue: true, + tabindex: true, + bindKeypress: true, + bindRoleForClick: true + }; + + /** + * @ngdoc method + * @name $ariaProvider#config + * + * @param {object} config object to enable/disable specific ARIA attributes + * + * - **ariaHidden** – `{boolean}` – Enables/disables aria-hidden tags + * - **ariaChecked** – `{boolean}` – Enables/disables aria-checked tags + * - **ariaReadonly** – `{boolean}` – Enables/disables aria-readonly tags + * - **ariaDisabled** – `{boolean}` – Enables/disables aria-disabled tags + * - **ariaRequired** – `{boolean}` – Enables/disables aria-required tags + * - **ariaInvalid** – `{boolean}` – Enables/disables aria-invalid tags + * - **ariaValue** – `{boolean}` – Enables/disables aria-valuemin, aria-valuemax and aria-valuenow tags + * - **tabindex** – `{boolean}` – Enables/disables tabindex tags + * - **bindKeypress** – `{boolean}` – Enables/disables keypress event binding on `div` and + * `li` elements with ng-click + * - **bindRoleForClick** – `{boolean}` – Adds role=button to non-interactive elements like `div` + * using ng-click, making them more accessible to users of assistive technologies + * + * @description + * Enables/disables various ARIA attributes + */ + this.config = function(newConfig) { + config = angular.extend(config, newConfig); + }; + + function watchExpr(attrName, ariaAttr, nodeBlackList, negate) { + return function(scope, elem, attr) { + var ariaCamelName = attr.$normalize(ariaAttr); + if (config[ariaCamelName] && !isNodeOneOf(elem, nodeBlackList) && !attr[ariaCamelName]) { + scope.$watch(attr[attrName], function(boolVal) { + // ensure boolean value + boolVal = negate ? !boolVal : !!boolVal; + elem.attr(ariaAttr, boolVal); + }); + } + }; + } + /** + * @ngdoc service + * @name $aria + * + * @description + * @priority 200 + * + * The $aria service contains helper methods for applying common + * [ARIA](http://www.w3.org/TR/wai-aria/) attributes to HTML directives. + * + * ngAria injects common accessibility attributes that tell assistive technologies when HTML + * elements are enabled, selected, hidden, and more. To see how this is performed with ngAria, + * let's review a code snippet from ngAria itself: + * + *```js + * ngAriaModule.directive('ngDisabled', ['$aria', function($aria) { + * return $aria.$$watchExpr('ngDisabled', 'aria-disabled', nodeBlackList, false); + * }]) + *``` + * Shown above, the ngAria module creates a directive with the same signature as the + * traditional `ng-disabled` directive. But this ngAria version is dedicated to + * solely managing accessibility attributes on custom elements. The internal `$aria` service is + * used to watch the boolean attribute `ngDisabled`. If it has not been explicitly set by the + * developer, `aria-disabled` is injected as an attribute with its value synchronized to the + * value in `ngDisabled`. + * + * Because ngAria hooks into the `ng-disabled` directive, developers do not have to do + * anything to enable this feature. The `aria-disabled` attribute is automatically managed + * simply as a silent side-effect of using `ng-disabled` with the ngAria module. + * + * The full list of directives that interface with ngAria: + * * **ngModel** + * * **ngChecked** + * * **ngReadonly** + * * **ngRequired** + * * **ngDisabled** + * * **ngValue** + * * **ngShow** + * * **ngHide** + * * **ngClick** + * * **ngDblclick** + * * **ngMessages** + * + * Read the {@link guide/accessibility ngAria Developer Guide} for a thorough explanation of each + * directive. + * + * + * ## Dependencies + * Requires the {@link ngAria} module to be installed. + */ + this.$get = function() { + return { + config: function(key) { + return config[key]; + }, + $$watchExpr: watchExpr + }; + }; +} + + +ngAriaModule.directive('ngShow', ['$aria', function($aria) { + return $aria.$$watchExpr('ngShow', 'aria-hidden', [], true); +}]) +.directive('ngHide', ['$aria', function($aria) { + return $aria.$$watchExpr('ngHide', 'aria-hidden', [], false); +}]) +.directive('ngValue', ['$aria', function($aria) { + return $aria.$$watchExpr('ngValue', 'aria-checked', nodeBlackList, false); +}]) +.directive('ngChecked', ['$aria', function($aria) { + return $aria.$$watchExpr('ngChecked', 'aria-checked', nodeBlackList, false); +}]) +.directive('ngReadonly', ['$aria', function($aria) { + return $aria.$$watchExpr('ngReadonly', 'aria-readonly', nodeBlackList, false); +}]) +.directive('ngRequired', ['$aria', function($aria) { + return $aria.$$watchExpr('ngRequired', 'aria-required', nodeBlackList, false); +}]) +.directive('ngModel', ['$aria', function($aria) { + + function shouldAttachAttr(attr, normalizedAttr, elem, allowBlacklistEls) { + return $aria.config(normalizedAttr) && !elem.attr(attr) && (allowBlacklistEls || !isNodeOneOf(elem, nodeBlackList)); + } + + function shouldAttachRole(role, elem) { + // if element does not have role attribute + // AND element type is equal to role (if custom element has a type equaling shape) <-- remove? + // AND element is not INPUT + return !elem.attr('role') && (elem.attr('type') === role) && (elem[0].nodeName !== 'INPUT'); + } + + function getShape(attr, elem) { + var type = attr.type, + role = attr.role; + + return ((type || role) === 'checkbox' || role === 'menuitemcheckbox') ? 'checkbox' : + ((type || role) === 'radio' || role === 'menuitemradio') ? 'radio' : + (type === 'range' || role === 'progressbar' || role === 'slider') ? 'range' : ''; + } + + return { + restrict: 'A', + require: 'ngModel', + priority: 200, //Make sure watches are fired after any other directives that affect the ngModel value + compile: function(elem, attr) { + var shape = getShape(attr, elem); + + return { + pre: function(scope, elem, attr, ngModel) { + if (shape === 'checkbox') { + //Use the input[checkbox] $isEmpty implementation for elements with checkbox roles + ngModel.$isEmpty = function(value) { + return value === false; + }; + } + }, + post: function(scope, elem, attr, ngModel) { + var needsTabIndex = shouldAttachAttr('tabindex', 'tabindex', elem, false); + + function ngAriaWatchModelValue() { + return ngModel.$modelValue; + } + + function getRadioReaction(newVal) { + var boolVal = (attr.value == ngModel.$viewValue); + elem.attr('aria-checked', boolVal); + } + + function getCheckboxReaction() { + elem.attr('aria-checked', !ngModel.$isEmpty(ngModel.$viewValue)); + } + + switch (shape) { + case 'radio': + case 'checkbox': + if (shouldAttachRole(shape, elem)) { + elem.attr('role', shape); + } + if (shouldAttachAttr('aria-checked', 'ariaChecked', elem, false)) { + scope.$watch(ngAriaWatchModelValue, shape === 'radio' ? + getRadioReaction : getCheckboxReaction); + } + if (needsTabIndex) { + elem.attr('tabindex', 0); + } + break; + case 'range': + if (shouldAttachRole(shape, elem)) { + elem.attr('role', 'slider'); + } + if ($aria.config('ariaValue')) { + var needsAriaValuemin = !elem.attr('aria-valuemin') && + (attr.hasOwnProperty('min') || attr.hasOwnProperty('ngMin')); + var needsAriaValuemax = !elem.attr('aria-valuemax') && + (attr.hasOwnProperty('max') || attr.hasOwnProperty('ngMax')); + var needsAriaValuenow = !elem.attr('aria-valuenow'); + + if (needsAriaValuemin) { + attr.$observe('min', function ngAriaValueMinReaction(newVal) { + elem.attr('aria-valuemin', newVal); + }); + } + if (needsAriaValuemax) { + attr.$observe('max', function ngAriaValueMinReaction(newVal) { + elem.attr('aria-valuemax', newVal); + }); + } + if (needsAriaValuenow) { + scope.$watch(ngAriaWatchModelValue, function ngAriaValueNowReaction(newVal) { + elem.attr('aria-valuenow', newVal); + }); + } + } + if (needsTabIndex) { + elem.attr('tabindex', 0); + } + break; + } + + if (!attr.hasOwnProperty('ngRequired') && ngModel.$validators.required + && shouldAttachAttr('aria-required', 'ariaRequired', elem, false)) { + // ngModel.$error.required is undefined on custom controls + attr.$observe('required', function() { + elem.attr('aria-required', !!attr['required']); + }); + } + + if (shouldAttachAttr('aria-invalid', 'ariaInvalid', elem, true)) { + scope.$watch(function ngAriaInvalidWatch() { + return ngModel.$invalid; + }, function ngAriaInvalidReaction(newVal) { + elem.attr('aria-invalid', !!newVal); + }); + } + } + }; + } + }; +}]) +.directive('ngDisabled', ['$aria', function($aria) { + return $aria.$$watchExpr('ngDisabled', 'aria-disabled', nodeBlackList, false); +}]) +.directive('ngMessages', function() { + return { + restrict: 'A', + require: '?ngMessages', + link: function(scope, elem, attr, ngMessages) { + if (!elem.attr('aria-live')) { + elem.attr('aria-live', 'assertive'); + } + } + }; +}) +.directive('ngClick',['$aria', '$parse', function($aria, $parse) { + return { + restrict: 'A', + compile: function(elem, attr) { + var fn = $parse(attr.ngClick, /* interceptorFn */ null, /* expensiveChecks */ true); + return function(scope, elem, attr) { + + if (!isNodeOneOf(elem, nodeBlackList)) { + + if ($aria.config('bindRoleForClick') && !elem.attr('role')) { + elem.attr('role', 'button'); + } + + if ($aria.config('tabindex') && !elem.attr('tabindex')) { + elem.attr('tabindex', 0); + } + + if ($aria.config('bindKeypress') && !attr.ngKeypress) { + elem.on('keypress', function(event) { + var keyCode = event.which || event.keyCode; + if (keyCode === 32 || keyCode === 13) { + scope.$apply(callback); + } + + function callback() { + fn(scope, { $event: event }); + } + }); + } + } + }; + } + }; +}]) +.directive('ngDblclick', ['$aria', function($aria) { + return function(scope, elem, attr) { + if ($aria.config('tabindex') && !elem.attr('tabindex') && !isNodeOneOf(elem, nodeBlackList)) { + elem.attr('tabindex', 0); + } + }; +}]); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-aria.min.js b/src/main/resources/static/module/angular/angular-aria.min.js new file mode 100644 index 0000000..94e2020 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-aria.min.js @@ -0,0 +1,14 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(t,p){'use strict';var b="BUTTON A INPUT TEXTAREA SELECT DETAILS SUMMARY".split(" "),l=function(a,c){if(-1!==c.indexOf(a[0].nodeName))return!0};p.module("ngAria",["ng"]).provider("$aria",function(){function a(a,b,m,h){return function(d,f,e){var q=e.$normalize(b);!c[q]||l(f,m)||e[q]||d.$watch(e[a],function(a){a=h?!a:!!a;f.attr(b,a)})}}var c={ariaHidden:!0,ariaChecked:!0,ariaReadonly:!0,ariaDisabled:!0,ariaRequired:!0,ariaInvalid:!0,ariaValue:!0,tabindex:!0,bindKeypress:!0,bindRoleForClick:!0}; +this.config=function(a){c=p.extend(c,a)};this.$get=function(){return{config:function(a){return c[a]},$$watchExpr:a}}}).directive("ngShow",["$aria",function(a){return a.$$watchExpr("ngShow","aria-hidden",[],!0)}]).directive("ngHide",["$aria",function(a){return a.$$watchExpr("ngHide","aria-hidden",[],!1)}]).directive("ngValue",["$aria",function(a){return a.$$watchExpr("ngValue","aria-checked",b,!1)}]).directive("ngChecked",["$aria",function(a){return a.$$watchExpr("ngChecked","aria-checked",b,!1)}]).directive("ngReadonly", +["$aria",function(a){return a.$$watchExpr("ngReadonly","aria-readonly",b,!1)}]).directive("ngRequired",["$aria",function(a){return a.$$watchExpr("ngRequired","aria-required",b,!1)}]).directive("ngModel",["$aria",function(a){function c(c,h,d,f){return a.config(h)&&!d.attr(c)&&(f||!l(d,b))}function g(a,c){return!c.attr("role")&&c.attr("type")===a&&"INPUT"!==c[0].nodeName}function k(a,c){var d=a.type,f=a.role;return"checkbox"===(d||f)||"menuitemcheckbox"===f?"checkbox":"radio"===(d||f)||"menuitemradio"=== +f?"radio":"range"===d||"progressbar"===f||"slider"===f?"range":""}return{restrict:"A",require:"ngModel",priority:200,compile:function(b,h){var d=k(h,b);return{pre:function(a,e,c,b){"checkbox"===d&&(b.$isEmpty=function(a){return!1===a})},post:function(f,e,b,n){function h(){return n.$modelValue}function k(a){e.attr("aria-checked",b.value==n.$viewValue)}function l(){e.attr("aria-checked",!n.$isEmpty(n.$viewValue))}var m=c("tabindex","tabindex",e,!1);switch(d){case "radio":case "checkbox":g(d,e)&&e.attr("role", +d);c("aria-checked","ariaChecked",e,!1)&&f.$watch(h,"radio"===d?k:l);m&&e.attr("tabindex",0);break;case "range":g(d,e)&&e.attr("role","slider");if(a.config("ariaValue")){var p=!e.attr("aria-valuemin")&&(b.hasOwnProperty("min")||b.hasOwnProperty("ngMin")),r=!e.attr("aria-valuemax")&&(b.hasOwnProperty("max")||b.hasOwnProperty("ngMax")),s=!e.attr("aria-valuenow");p&&b.$observe("min",function(a){e.attr("aria-valuemin",a)});r&&b.$observe("max",function(a){e.attr("aria-valuemax",a)});s&&f.$watch(h,function(a){e.attr("aria-valuenow", +a)})}m&&e.attr("tabindex",0)}!b.hasOwnProperty("ngRequired")&&n.$validators.required&&c("aria-required","ariaRequired",e,!1)&&b.$observe("required",function(){e.attr("aria-required",!!b.required)});c("aria-invalid","ariaInvalid",e,!0)&&f.$watch(function(){return n.$invalid},function(a){e.attr("aria-invalid",!!a)})}}}}}]).directive("ngDisabled",["$aria",function(a){return a.$$watchExpr("ngDisabled","aria-disabled",b,!1)}]).directive("ngMessages",function(){return{restrict:"A",require:"?ngMessages", +link:function(a,b,g,k){b.attr("aria-live")||b.attr("aria-live","assertive")}}}).directive("ngClick",["$aria","$parse",function(a,c){return{restrict:"A",compile:function(g,k){var m=c(k.ngClick,null,!0);return function(c,d,f){if(!l(d,b)&&(a.config("bindRoleForClick")&&!d.attr("role")&&d.attr("role","button"),a.config("tabindex")&&!d.attr("tabindex")&&d.attr("tabindex",0),a.config("bindKeypress")&&!f.ngKeypress))d.on("keypress",function(a){function b(){m(c,{$event:a})}var d=a.which||a.keyCode;32!==d&& +13!==d||c.$apply(b)})}}}}]).directive("ngDblclick",["$aria",function(a){return function(c,g,k){!a.config("tabindex")||g.attr("tabindex")||l(g,b)||g.attr("tabindex",0)}}])})(window,window.angular); +//# sourceMappingURL=angular-aria.min.js.map diff --git a/src/main/resources/static/module/angular/angular-aria.min.js.map b/src/main/resources/static/module/angular/angular-aria.min.js.map new file mode 100644 index 0000000..925779b --- /dev/null +++ b/src/main/resources/static/module/angular/angular-aria.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-aria.min.js", +"lineCount":13, +"mappings":"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", +"sources":["angular-aria.js"], +"names":["window","angular","nodeBlackList","isNodeOneOf","elem","nodeTypeArray","indexOf","nodeName","module","provider","ngAriaModule","$AriaProvider","watchExpr","attrName","ariaAttr","negate","scope","attr","ariaCamelName","$normalize","config","$watch","boolVal","ariaHidden","ariaChecked","ariaReadonly","ariaDisabled","ariaRequired","ariaInvalid","ariaValue","tabindex","bindKeypress","bindRoleForClick","this.config","newConfig","extend","$get","this.$get","key","$$watchExpr","directive","$aria","shouldAttachAttr","normalizedAttr","allowBlacklistEls","shouldAttachRole","role","getShape","type","restrict","require","priority","compile","shape","pre","ngModel","$isEmpty","ngModel.$isEmpty","value","post","ngAriaWatchModelValue","$modelValue","getRadioReaction","newVal","$viewValue","getCheckboxReaction","needsTabIndex","needsAriaValuemin","hasOwnProperty","needsAriaValuemax","needsAriaValuenow","$observe","ngAriaValueMinReaction","ngAriaValueNowReaction","$validators","required","ngAriaInvalidWatch","$invalid","ngAriaInvalidReaction","link","ngMessages","$parse","fn","ngClick","ngKeypress","on","event","callback","$event","keyCode","which","$apply"] +} diff --git a/src/main/resources/static/module/angular/angular-cookies.js b/src/main/resources/static/module/angular/angular-cookies.js new file mode 100644 index 0000000..a03ff49 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-cookies.js @@ -0,0 +1,322 @@ +/** + * @license AngularJS v1.5.8 + * (c) 2010-2016 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular) {'use strict'; + +/** + * @ngdoc module + * @name ngCookies + * @description + * + * # ngCookies + * + * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. + * + * + *
    + * + * See {@link ngCookies.$cookies `$cookies`} for usage. + */ + + +angular.module('ngCookies', ['ng']). + /** + * @ngdoc provider + * @name $cookiesProvider + * @description + * Use `$cookiesProvider` to change the default behavior of the {@link ngCookies.$cookies $cookies} service. + * */ + provider('$cookies', [function $CookiesProvider() { + /** + * @ngdoc property + * @name $cookiesProvider#defaults + * @description + * + * Object containing default options to pass when setting cookies. + * + * The object may have following properties: + * + * - **path** - `{string}` - The cookie will be available only for this path and its + * sub-paths. By default, this is the URL that appears in your `` tag. + * - **domain** - `{string}` - The cookie will be available only for this domain and + * its sub-domains. For security reasons the user agent will not accept the cookie + * if the current domain is not a sub-domain of this domain or equal to it. + * - **expires** - `{string|Date}` - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" + * or a Date object indicating the exact date/time this cookie will expire. + * - **secure** - `{boolean}` - If `true`, then the cookie will only be available through a + * secured connection. + * + * Note: By default, the address that appears in your `` tag will be used as the path. + * This is important so that cookies will be visible for all routes when html5mode is enabled. + * + **/ + var defaults = this.defaults = {}; + + function calcOptions(options) { + return options ? angular.extend({}, defaults, options) : defaults; + } + + /** + * @ngdoc service + * @name $cookies + * + * @description + * Provides read/write access to browser's cookies. + * + *
    + * Up until Angular 1.3, `$cookies` exposed properties that represented the + * current browser cookie values. In version 1.4, this behavior has changed, and + * `$cookies` now provides a standard api of getters, setters etc. + *
    + * + * Requires the {@link ngCookies `ngCookies`} module to be installed. + * + * @example + * + * ```js + * angular.module('cookiesExample', ['ngCookies']) + * .controller('ExampleController', ['$cookies', function($cookies) { + * // Retrieving a cookie + * var favoriteCookie = $cookies.get('myFavorite'); + * // Setting a cookie + * $cookies.put('myFavorite', 'oatmeal'); + * }]); + * ``` + */ + this.$get = ['$$cookieReader', '$$cookieWriter', function($$cookieReader, $$cookieWriter) { + return { + /** + * @ngdoc method + * @name $cookies#get + * + * @description + * Returns the value of given cookie key + * + * @param {string} key Id to use for lookup. + * @returns {string} Raw cookie value. + */ + get: function(key) { + return $$cookieReader()[key]; + }, + + /** + * @ngdoc method + * @name $cookies#getObject + * + * @description + * Returns the deserialized value of given cookie key + * + * @param {string} key Id to use for lookup. + * @returns {Object} Deserialized cookie value. + */ + getObject: function(key) { + var value = this.get(key); + return value ? angular.fromJson(value) : value; + }, + + /** + * @ngdoc method + * @name $cookies#getAll + * + * @description + * Returns a key value object with all the cookies + * + * @returns {Object} All cookies + */ + getAll: function() { + return $$cookieReader(); + }, + + /** + * @ngdoc method + * @name $cookies#put + * + * @description + * Sets a value for given cookie key + * + * @param {string} key Id for the `value`. + * @param {string} value Raw value to be stored. + * @param {Object=} options Options object. + * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} + */ + put: function(key, value, options) { + $$cookieWriter(key, value, calcOptions(options)); + }, + + /** + * @ngdoc method + * @name $cookies#putObject + * + * @description + * Serializes and sets a value for given cookie key + * + * @param {string} key Id for the `value`. + * @param {Object} value Value to be stored. + * @param {Object=} options Options object. + * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} + */ + putObject: function(key, value, options) { + this.put(key, angular.toJson(value), options); + }, + + /** + * @ngdoc method + * @name $cookies#remove + * + * @description + * Remove given cookie + * + * @param {string} key Id of the key-value pair to delete. + * @param {Object=} options Options object. + * See {@link ngCookies.$cookiesProvider#defaults $cookiesProvider.defaults} + */ + remove: function(key, options) { + $$cookieWriter(key, undefined, calcOptions(options)); + } + }; + }]; + }]); + +angular.module('ngCookies'). +/** + * @ngdoc service + * @name $cookieStore + * @deprecated + * @requires $cookies + * + * @description + * Provides a key-value (string-object) storage, that is backed by session cookies. + * Objects put or retrieved from this storage are automatically serialized or + * deserialized by angular's toJson/fromJson. + * + * Requires the {@link ngCookies `ngCookies`} module to be installed. + * + *
    + * **Note:** The $cookieStore service is **deprecated**. + * Please use the {@link ngCookies.$cookies `$cookies`} service instead. + *
    + * + * @example + * + * ```js + * angular.module('cookieStoreExample', ['ngCookies']) + * .controller('ExampleController', ['$cookieStore', function($cookieStore) { + * // Put cookie + * $cookieStore.put('myFavorite','oatmeal'); + * // Get cookie + * var favoriteCookie = $cookieStore.get('myFavorite'); + * // Removing a cookie + * $cookieStore.remove('myFavorite'); + * }]); + * ``` + */ + factory('$cookieStore', ['$cookies', function($cookies) { + + return { + /** + * @ngdoc method + * @name $cookieStore#get + * + * @description + * Returns the value of given cookie key + * + * @param {string} key Id to use for lookup. + * @returns {Object} Deserialized cookie value, undefined if the cookie does not exist. + */ + get: function(key) { + return $cookies.getObject(key); + }, + + /** + * @ngdoc method + * @name $cookieStore#put + * + * @description + * Sets a value for given cookie key + * + * @param {string} key Id for the `value`. + * @param {Object} value Value to be stored. + */ + put: function(key, value) { + $cookies.putObject(key, value); + }, + + /** + * @ngdoc method + * @name $cookieStore#remove + * + * @description + * Remove given cookie + * + * @param {string} key Id of the key-value pair to delete. + */ + remove: function(key) { + $cookies.remove(key); + } + }; + + }]); + +/** + * @name $$cookieWriter + * @requires $document + * + * @description + * This is a private service for writing cookies + * + * @param {string} name Cookie name + * @param {string=} value Cookie value (if undefined, cookie will be deleted) + * @param {Object=} options Object with options that need to be stored for the cookie. + */ +function $$CookieWriter($document, $log, $browser) { + var cookiePath = $browser.baseHref(); + var rawDocument = $document[0]; + + function buildCookieString(name, value, options) { + var path, expires; + options = options || {}; + expires = options.expires; + path = angular.isDefined(options.path) ? options.path : cookiePath; + if (angular.isUndefined(value)) { + expires = 'Thu, 01 Jan 1970 00:00:00 GMT'; + value = ''; + } + if (angular.isString(expires)) { + expires = new Date(expires); + } + + var str = encodeURIComponent(name) + '=' + encodeURIComponent(value); + str += path ? ';path=' + path : ''; + str += options.domain ? ';domain=' + options.domain : ''; + str += expires ? ';expires=' + expires.toUTCString() : ''; + str += options.secure ? ';secure' : ''; + + // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: + // - 300 cookies + // - 20 cookies per unique domain + // - 4096 bytes per cookie + var cookieLength = str.length + 1; + if (cookieLength > 4096) { + $log.warn("Cookie '" + name + + "' possibly not set or overflowed because it was too large (" + + cookieLength + " > 4096 bytes)!"); + } + + return str; + } + + return function(name, value, options) { + rawDocument.cookie = buildCookieString(name, value, options); + }; +} + +$$CookieWriter.$inject = ['$document', '$log', '$browser']; + +angular.module('ngCookies').provider('$$cookieWriter', function $$CookieWriterProvider() { + this.$get = $$CookieWriter; +}); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-cookies.min.js b/src/main/resources/static/module/angular/angular-cookies.min.js new file mode 100644 index 0000000..d767aee --- /dev/null +++ b/src/main/resources/static/module/angular/angular-cookies.min.js @@ -0,0 +1,9 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(n,c){'use strict';function l(b,a,g){var d=g.baseHref(),k=b[0];return function(b,e,f){var g,h;f=f||{};h=f.expires;g=c.isDefined(f.path)?f.path:d;c.isUndefined(e)&&(h="Thu, 01 Jan 1970 00:00:00 GMT",e="");c.isString(h)&&(h=new Date(h));e=encodeURIComponent(b)+"="+encodeURIComponent(e);e=e+(g?";path="+g:"")+(f.domain?";domain="+f.domain:"");e+=h?";expires="+h.toUTCString():"";e+=f.secure?";secure":"";f=e.length+1;4096 4096 bytes)!");k.cookie=e}}c.module("ngCookies",["ng"]).provider("$cookies",[function(){var b=this.defaults={};this.$get=["$$cookieReader","$$cookieWriter",function(a,g){return{get:function(d){return a()[d]},getObject:function(d){return(d=this.get(d))?c.fromJson(d):d},getAll:function(){return a()},put:function(d,a,m){g(d,a,m?c.extend({},b,m):b)},putObject:function(d,b,a){this.put(d,c.toJson(b),a)},remove:function(a,k){g(a,void 0,k?c.extend({},b,k):b)}}}]}]);c.module("ngCookies").factory("$cookieStore", +["$cookies",function(b){return{get:function(a){return b.getObject(a)},put:function(a,c){b.putObject(a,c)},remove:function(a){b.remove(a)}}}]);l.$inject=["$document","$log","$browser"];c.module("ngCookies").provider("$$cookieWriter",function(){this.$get=l})})(window,window.angular); +//# sourceMappingURL=angular-cookies.min.js.map diff --git a/src/main/resources/static/module/angular/angular-cookies.min.js.map b/src/main/resources/static/module/angular/angular-cookies.min.js.map new file mode 100644 index 0000000..42f748a --- /dev/null +++ b/src/main/resources/static/module/angular/angular-cookies.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-cookies.min.js", +"lineCount":8, +"mappings":"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", +"sources":["angular-cookies.js"], +"names":["window","angular","$$CookieWriter","$document","$log","$browser","cookiePath","baseHref","rawDocument","name","value","options","path","expires","isDefined","isUndefined","isString","Date","str","encodeURIComponent","domain","toUTCString","secure","cookieLength","length","warn","cookie","module","provider","$CookiesProvider","defaults","$get","$$cookieReader","$$cookieWriter","get","key","getObject","fromJson","getAll","put","extend","putObject","toJson","remove","undefined","factory","$cookies","$inject","$$CookieWriterProvider"] +} diff --git a/src/main/resources/static/module/angular/angular-csp.css b/src/main/resources/static/module/angular/angular-csp.css new file mode 100644 index 0000000..f3cd926 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-csp.css @@ -0,0 +1,21 @@ +/* Include this file in your html if you are using the CSP mode. */ + +@charset "UTF-8"; + +[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], +.ng-cloak, .x-ng-cloak, +.ng-hide:not(.ng-hide-animate) { + display: none !important; +} + +ng\:form { + display: block; +} + +.ng-animate-shim { + visibility:hidden; +} + +.ng-anchor { + position:absolute; +} diff --git a/src/main/resources/static/module/angular/angular-loader.js b/src/main/resources/static/module/angular/angular-loader.js new file mode 100644 index 0000000..b005220 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-loader.js @@ -0,0 +1,484 @@ +/** + * @license AngularJS v1.5.8 + * (c) 2010-2016 Google, Inc. http://angularjs.org + * License: MIT + */ + +(function() {'use strict'; + function isFunction(value) {return typeof value === 'function';}; + +/* global toDebugString: true */ + +function serializeObject(obj) { + var seen = []; + + return JSON.stringify(obj, function(key, val) { + val = toJsonReplacer(key, val); + if (isObject(val)) { + + if (seen.indexOf(val) >= 0) return '...'; + + seen.push(val); + } + return val; + }); +} + +function toDebugString(obj) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (isUndefined(obj)) { + return 'undefined'; + } else if (typeof obj !== 'string') { + return serializeObject(obj); + } + return obj; +} + +/** + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning + * error from returned function, for cases when a particular type of error is useful. + * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance + */ + +function minErr(module, ErrorConstructor) { + ErrorConstructor = ErrorConstructor || Error; + return function() { + var SKIP_INDEXES = 2; + + var templateArgs = arguments, + code = templateArgs[0], + message = '[' + (module ? module + ':' : '') + code + '] ', + template = templateArgs[1], + paramPrefix, i; + + message += template.replace(/\{\d+\}/g, function(match) { + var index = +match.slice(1, -1), + shiftedIndex = index + SKIP_INDEXES; + + if (shiftedIndex < templateArgs.length) { + return toDebugString(templateArgs[shiftedIndex]); + } + + return match; + }); + + message += '\nhttp://errors.angularjs.org/1.5.8/' + + (module ? module + '/' : '') + code; + + for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { + message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' + + encodeURIComponent(toDebugString(templateArgs[i])); + } + + return new ErrorConstructor(message); + }; +} + +/** + * @ngdoc type + * @name angular.Module + * @module ng + * @description + * + * Interface for configuring angular {@link angular.module modules}. + */ + +function setupModuleLoader(window) { + + var $injectorMinErr = minErr('$injector'); + var ngMinErr = minErr('ng'); + + function ensure(obj, name, factory) { + return obj[name] || (obj[name] = factory()); + } + + var angular = ensure(window, 'angular', Object); + + // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap + angular.$$minErr = angular.$$minErr || minErr; + + return ensure(angular, 'module', function() { + /** @type {Object.} */ + var modules = {}; + + /** + * @ngdoc function + * @name angular.module + * @module ng + * @description + * + * The `angular.module` is a global place for creating, registering and retrieving Angular + * modules. + * All modules (angular core or 3rd party) that should be available to an application must be + * registered using this mechanism. + * + * Passing one argument retrieves an existing {@link angular.Module}, + * whereas passing more than one argument creates a new {@link angular.Module} + * + * + * # Module + * + * A module is a collection of services, directives, controllers, filters, and configuration information. + * `angular.module` is used to configure the {@link auto.$injector $injector}. + * + * ```js + * // Create a new module + * var myModule = angular.module('myModule', []); + * + * // register a new service + * myModule.value('appName', 'MyCoolApp'); + * + * // configure existing services inside initialization blocks. + * myModule.config(['$locationProvider', function($locationProvider) { + * // Configure existing providers + * $locationProvider.hashPrefix('!'); + * }]); + * ``` + * + * Then you can create an injector and load your modules like this: + * + * ```js + * var injector = angular.injector(['ng', 'myModule']) + * ``` + * + * However it's more likely that you'll just use + * {@link ng.directive:ngApp ngApp} or + * {@link angular.bootstrap} to simplify this process for you. + * + * @param {!string} name The name of the module to create or retrieve. + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as + * {@link angular.Module#config Module#config()}. + * @returns {angular.Module} new module with the {@link angular.Module} api. + */ + return function module(name, requires, configFn) { + var assertNotHasOwnProperty = function(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); + } + }; + + assertNotHasOwnProperty(name, 'module'); + if (requires && modules.hasOwnProperty(name)) { + modules[name] = null; + } + return ensure(modules, name, function() { + if (!requires) { + throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + + "the module name or forgot to load it. If registering a module ensure that you " + + "specify the dependencies as the second argument.", name); + } + + /** @type {!Array.>} */ + var invokeQueue = []; + + /** @type {!Array.} */ + var configBlocks = []; + + /** @type {!Array.} */ + var runBlocks = []; + + var config = invokeLater('$injector', 'invoke', 'push', configBlocks); + + /** @type {angular.Module} */ + var moduleInstance = { + // Private state + _invokeQueue: invokeQueue, + _configBlocks: configBlocks, + _runBlocks: runBlocks, + + /** + * @ngdoc property + * @name angular.Module#requires + * @module ng + * + * @description + * Holds the list of modules which the injector will load before the current module is + * loaded. + */ + requires: requires, + + /** + * @ngdoc property + * @name angular.Module#name + * @module ng + * + * @description + * Name of the module. + */ + name: name, + + + /** + * @ngdoc method + * @name angular.Module#provider + * @module ng + * @param {string} name service name + * @param {Function} providerType Construction function for creating new instance of the + * service. + * @description + * See {@link auto.$provide#provider $provide.provider()}. + */ + provider: invokeLaterAndSetModuleName('$provide', 'provider'), + + /** + * @ngdoc method + * @name angular.Module#factory + * @module ng + * @param {string} name service name + * @param {Function} providerFunction Function for creating new instance of the service. + * @description + * See {@link auto.$provide#factory $provide.factory()}. + */ + factory: invokeLaterAndSetModuleName('$provide', 'factory'), + + /** + * @ngdoc method + * @name angular.Module#service + * @module ng + * @param {string} name service name + * @param {Function} constructor A constructor function that will be instantiated. + * @description + * See {@link auto.$provide#service $provide.service()}. + */ + service: invokeLaterAndSetModuleName('$provide', 'service'), + + /** + * @ngdoc method + * @name angular.Module#value + * @module ng + * @param {string} name service name + * @param {*} object Service instance object. + * @description + * See {@link auto.$provide#value $provide.value()}. + */ + value: invokeLater('$provide', 'value'), + + /** + * @ngdoc method + * @name angular.Module#constant + * @module ng + * @param {string} name constant name + * @param {*} object Constant value. + * @description + * Because the constants are fixed, they get applied before other provide methods. + * See {@link auto.$provide#constant $provide.constant()}. + */ + constant: invokeLater('$provide', 'constant', 'unshift'), + + /** + * @ngdoc method + * @name angular.Module#decorator + * @module ng + * @param {string} name The name of the service to decorate. + * @param {Function} decorFn This function will be invoked when the service needs to be + * instantiated and should return the decorated service instance. + * @description + * See {@link auto.$provide#decorator $provide.decorator()}. + */ + decorator: invokeLaterAndSetModuleName('$provide', 'decorator'), + + /** + * @ngdoc method + * @name angular.Module#animation + * @module ng + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an + * animation. + * @description + * + * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. + * + * + * Defines an animation hook that can be later used with + * {@link $animate $animate} service and directives that use this service. + * + * ```js + * module.animation('.animation-name', function($inject1, $inject2) { + * return { + * eventName : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction(element) { + * //code to cancel the animation + * } + * } + * } + * }) + * ``` + * + * See {@link ng.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLaterAndSetModuleName('$animateProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#filter + * @module ng + * @param {string} name Filter name - this must be a valid angular expression identifier + * @param {Function} filterFactory Factory function for creating new instance of filter. + * @description + * See {@link ng.$filterProvider#register $filterProvider.register()}. + * + *
    + * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
    + */ + filter: invokeLaterAndSetModuleName('$filterProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#controller + * @module ng + * @param {string|Object} name Controller name, or an object map of controllers where the + * keys are the names and the values are the constructors. + * @param {Function} constructor Controller constructor function. + * @description + * See {@link ng.$controllerProvider#register $controllerProvider.register()}. + */ + controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#directive + * @module ng + * @param {string|Object} name Directive name, or an object map of directives where the + * keys are the names and the values are the factories. + * @param {Function} directiveFactory Factory function for creating new instance of + * directives. + * @description + * See {@link ng.$compileProvider#directive $compileProvider.directive()}. + */ + directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'), + + /** + * @ngdoc method + * @name angular.Module#component + * @module ng + * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp) + * @param {Object} options Component definition object (a simplified + * {@link ng.$compile#directive-definition-object directive definition object}) + * + * @description + * See {@link ng.$compileProvider#component $compileProvider.component()}. + */ + component: invokeLaterAndSetModuleName('$compileProvider', 'component'), + + /** + * @ngdoc method + * @name angular.Module#config + * @module ng + * @param {Function} configFn Execute this function on module load. Useful for service + * configuration. + * @description + * Use this method to register work which needs to be performed on module loading. + * For more about how to configure services, see + * {@link providers#provider-recipe Provider Recipe}. + */ + config: config, + + /** + * @ngdoc method + * @name angular.Module#run + * @module ng + * @param {Function} initializationFn Execute this function after injector creation. + * Useful for application initialization. + * @description + * Use this method to register work which should be performed when the injector is done + * loading all modules. + */ + run: function(block) { + runBlocks.push(block); + return this; + } + }; + + if (configFn) { + config(configFn); + } + + return moduleInstance; + + /** + * @param {string} provider + * @param {string} method + * @param {String=} insertMethod + * @returns {angular.Module} + */ + function invokeLater(provider, method, insertMethod, queue) { + if (!queue) queue = invokeQueue; + return function() { + queue[insertMethod || 'push']([provider, method, arguments]); + return moduleInstance; + }; + } + + /** + * @param {string} provider + * @param {string} method + * @returns {angular.Module} + */ + function invokeLaterAndSetModuleName(provider, method) { + return function(recipeName, factoryFunction) { + if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name; + invokeQueue.push([provider, method, arguments]); + return moduleInstance; + }; + } + }); + }; + }); + +} + +setupModuleLoader(window); +})(window); + +/** + * Closure compiler type information + * + * @typedef { { + * requires: !Array., + * invokeQueue: !Array.>, + * + * service: function(string, Function):angular.Module, + * factory: function(string, Function):angular.Module, + * value: function(string, *):angular.Module, + * + * filter: function(string, Function):angular.Module, + * + * init: function(Function):angular.Module + * } } + */ +angular.Module; + diff --git a/src/main/resources/static/module/angular/angular-loader.min.js b/src/main/resources/static/module/angular/angular-loader.min.js new file mode 100644 index 0000000..b5efbce --- /dev/null +++ b/src/main/resources/static/module/angular/angular-loader.min.js @@ -0,0 +1,10 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(){'use strict';function d(b){return function(){var a=arguments[0],e;e="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.5.8/"+(b?b+"/":"")+a;for(a=1;a= line.length) { + index -= line.length; + } else { + return { line: i + 1, column: index + 1 }; + } + } +} +var PARSE_CACHE_FOR_TEXT_LITERALS = Object.create(null); + +function parseTextLiteral(text) { + var cachedFn = PARSE_CACHE_FOR_TEXT_LITERALS[text]; + if (cachedFn != null) { + return cachedFn; + } + function parsedFn(context) { return text; } + parsedFn['$$watchDelegate'] = function watchDelegate(scope, listener, objectEquality) { + var unwatch = scope['$watch'](noop, + function textLiteralWatcher() { + if (isFunction(listener)) { listener.call(null, text, text, scope); } + unwatch(); + }, + objectEquality); + return unwatch; + }; + PARSE_CACHE_FOR_TEXT_LITERALS[text] = parsedFn; + parsedFn['exp'] = text; // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js + parsedFn['expressions'] = []; // Require this to call $compile.$$addBindingInfo() which allows Protractor to find elements by binding. + return parsedFn; +} + +function subtractOffset(expressionFn, offset) { + if (offset === 0) { + return expressionFn; + } + function minusOffset(value) { + return (value == void 0) ? value : value - offset; + } + function parsedFn(context) { return minusOffset(expressionFn(context)); } + var unwatch; + parsedFn['$$watchDelegate'] = function watchDelegate(scope, listener, objectEquality) { + unwatch = scope['$watch'](expressionFn, + function pluralExpressionWatchListener(newValue, oldValue) { + if (isFunction(listener)) { listener.call(null, minusOffset(newValue), minusOffset(oldValue), scope); } + }, + objectEquality); + return unwatch; + }; + return parsedFn; +} + +// NOTE: ADVANCED_OPTIMIZATIONS mode. +// +// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using +// constructs incompatible with that mode. + +/* global $interpolateMinErr: false */ +/* global isFunction: false */ +/* global noop: false */ + +/** + * @constructor + * @private + */ +function MessageSelectorBase(expressionFn, choices) { + var self = this; + this.expressionFn = expressionFn; + this.choices = choices; + if (choices["other"] === void 0) { + throw $interpolateMinErr('reqother', '“other” is a required option.'); + } + this.parsedFn = function(context) { return self.getResult(context); }; + this.parsedFn['$$watchDelegate'] = function $$watchDelegate(scope, listener, objectEquality) { + return self.watchDelegate(scope, listener, objectEquality); + }; + this.parsedFn['exp'] = expressionFn['exp']; + this.parsedFn['expressions'] = expressionFn['expressions']; +} + +MessageSelectorBase.prototype.getMessageFn = function getMessageFn(value) { + return this.choices[this.categorizeValue(value)]; +}; + +MessageSelectorBase.prototype.getResult = function getResult(context) { + return this.getMessageFn(this.expressionFn(context))(context); +}; + +MessageSelectorBase.prototype.watchDelegate = function watchDelegate(scope, listener, objectEquality) { + var watchers = new MessageSelectorWatchers(this, scope, listener, objectEquality); + return function() { watchers.cancelWatch(); }; +}; + +/** + * @constructor + * @private + */ +function MessageSelectorWatchers(msgSelector, scope, listener, objectEquality) { + var self = this; + this.scope = scope; + this.msgSelector = msgSelector; + this.listener = listener; + this.objectEquality = objectEquality; + this.lastMessage = void 0; + this.messageFnWatcher = noop; + var expressionFnListener = function(newValue, oldValue) { return self.expressionFnListener(newValue, oldValue); }; + this.expressionFnWatcher = scope['$watch'](msgSelector.expressionFn, expressionFnListener, objectEquality); +} + +MessageSelectorWatchers.prototype.expressionFnListener = function expressionFnListener(newValue, oldValue) { + var self = this; + this.messageFnWatcher(); + var messageFnListener = function(newMessage, oldMessage) { return self.messageFnListener(newMessage, oldMessage); }; + var messageFn = this.msgSelector.getMessageFn(newValue); + this.messageFnWatcher = this.scope['$watch'](messageFn, messageFnListener, this.objectEquality); +}; + +MessageSelectorWatchers.prototype.messageFnListener = function messageFnListener(newMessage, oldMessage) { + if (isFunction(this.listener)) { + this.listener.call(null, newMessage, newMessage === oldMessage ? newMessage : this.lastMessage, this.scope); + } + this.lastMessage = newMessage; +}; + +MessageSelectorWatchers.prototype.cancelWatch = function cancelWatch() { + this.expressionFnWatcher(); + this.messageFnWatcher(); +}; + +/** + * @constructor + * @extends MessageSelectorBase + * @private + */ +function SelectMessage(expressionFn, choices) { + MessageSelectorBase.call(this, expressionFn, choices); +} + +function SelectMessageProto() {} +SelectMessageProto.prototype = MessageSelectorBase.prototype; + +SelectMessage.prototype = new SelectMessageProto(); +SelectMessage.prototype.categorizeValue = function categorizeSelectValue(value) { + return (this.choices[value] !== void 0) ? value : "other"; +}; + +/** + * @constructor + * @extends MessageSelectorBase + * @private + */ +function PluralMessage(expressionFn, choices, offset, pluralCat) { + MessageSelectorBase.call(this, expressionFn, choices); + this.offset = offset; + this.pluralCat = pluralCat; +} + +function PluralMessageProto() {} +PluralMessageProto.prototype = MessageSelectorBase.prototype; + +PluralMessage.prototype = new PluralMessageProto(); +PluralMessage.prototype.categorizeValue = function categorizePluralValue(value) { + if (isNaN(value)) { + return "other"; + } else if (this.choices[value] !== void 0) { + return value; + } else { + var category = this.pluralCat(value - this.offset); + return (this.choices[category] !== void 0) ? category : "other"; + } +}; + +// NOTE: ADVANCED_OPTIMIZATIONS mode. +// +// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using +// constructs incompatible with that mode. + +/* global $interpolateMinErr: false */ +/* global isFunction: false */ +/* global parseTextLiteral: false */ + +/** + * @constructor + * @private + */ +function InterpolationParts(trustedContext, allOrNothing) { + this.trustedContext = trustedContext; + this.allOrNothing = allOrNothing; + this.textParts = []; + this.expressionFns = []; + this.expressionIndices = []; + this.partialText = ''; + this.concatParts = null; +} + +InterpolationParts.prototype.flushPartialText = function flushPartialText() { + if (this.partialText) { + if (this.concatParts == null) { + this.textParts.push(this.partialText); + } else { + this.textParts.push(this.concatParts.join('')); + this.concatParts = null; + } + this.partialText = ''; + } +}; + +InterpolationParts.prototype.addText = function addText(text) { + if (text.length) { + if (!this.partialText) { + this.partialText = text; + } else if (this.concatParts) { + this.concatParts.push(text); + } else { + this.concatParts = [this.partialText, text]; + } + } +}; + +InterpolationParts.prototype.addExpressionFn = function addExpressionFn(expressionFn) { + this.flushPartialText(); + this.expressionIndices.push(this.textParts.length); + this.expressionFns.push(expressionFn); + this.textParts.push(''); +}; + +InterpolationParts.prototype.getExpressionValues = function getExpressionValues(context) { + var expressionValues = new Array(this.expressionFns.length); + for (var i = 0; i < this.expressionFns.length; i++) { + expressionValues[i] = this.expressionFns[i](context); + } + return expressionValues; +}; + +InterpolationParts.prototype.getResult = function getResult(expressionValues) { + for (var i = 0; i < this.expressionIndices.length; i++) { + var expressionValue = expressionValues[i]; + if (this.allOrNothing && expressionValue === void 0) return; + this.textParts[this.expressionIndices[i]] = expressionValue; + } + return this.textParts.join(''); +}; + + +InterpolationParts.prototype.toParsedFn = function toParsedFn(mustHaveExpression, originalText) { + var self = this; + this.flushPartialText(); + if (mustHaveExpression && this.expressionFns.length === 0) { + return void 0; + } + if (this.textParts.length === 0) { + return parseTextLiteral(''); + } + if (this.trustedContext && this.textParts.length > 1) { + $interpolateMinErr['throwNoconcat'](originalText); + } + if (this.expressionFns.length === 0) { + if (this.textParts.length != 1) { this.errorInParseLogic(); } + return parseTextLiteral(this.textParts[0]); + } + var parsedFn = function(context) { + return self.getResult(self.getExpressionValues(context)); + }; + parsedFn['$$watchDelegate'] = function $$watchDelegate(scope, listener, objectEquality) { + return self.watchDelegate(scope, listener, objectEquality); + }; + + parsedFn['exp'] = originalText; // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js + parsedFn['expressions'] = new Array(this.expressionFns.length); // Require this to call $compile.$$addBindingInfo() which allows Protractor to find elements by binding. + for (var i = 0; i < this.expressionFns.length; i++) { + parsedFn['expressions'][i] = this.expressionFns[i]['exp']; + } + + return parsedFn; +}; + +InterpolationParts.prototype.watchDelegate = function watchDelegate(scope, listener, objectEquality) { + var watcher = new InterpolationPartsWatcher(this, scope, listener, objectEquality); + return function() { watcher.cancelWatch(); }; +}; + +function InterpolationPartsWatcher(interpolationParts, scope, listener, objectEquality) { + this.interpolationParts = interpolationParts; + this.scope = scope; + this.previousResult = (void 0); + this.listener = listener; + var self = this; + this.expressionFnsWatcher = scope['$watchGroup'](interpolationParts.expressionFns, function(newExpressionValues, oldExpressionValues) { + self.watchListener(newExpressionValues, oldExpressionValues); + }); +} + +InterpolationPartsWatcher.prototype.watchListener = function watchListener(newExpressionValues, oldExpressionValues) { + var result = this.interpolationParts.getResult(newExpressionValues); + if (isFunction(this.listener)) { + this.listener.call(null, result, newExpressionValues === oldExpressionValues ? result : this.previousResult, this.scope); + } + this.previousResult = result; +}; + +InterpolationPartsWatcher.prototype.cancelWatch = function cancelWatch() { + this.expressionFnsWatcher(); +}; + +// NOTE: ADVANCED_OPTIMIZATIONS mode. +// +// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using +// constructs incompatible with that mode. + +/* global $interpolateMinErr: false */ +/* global indexToLineAndColumn: false */ +/* global InterpolationParts: false */ +/* global PluralMessage: false */ +/* global SelectMessage: false */ +/* global subtractOffset: false */ + +// The params src and dst are exactly one of two types: NestedParserState or MessageFormatParser. +// This function is fully optimized by V8. (inspect via IRHydra or --trace-deopt.) +// The idea behind writing it this way is to avoid repeating oneself. This is the ONE place where +// the parser state that is saved/restored when parsing nested mustaches is specified. +function copyNestedParserState(src, dst) { + dst.expressionFn = src.expressionFn; + dst.expressionMinusOffsetFn = src.expressionMinusOffsetFn; + dst.pluralOffset = src.pluralOffset; + dst.choices = src.choices; + dst.choiceKey = src.choiceKey; + dst.interpolationParts = src.interpolationParts; + dst.ruleChoiceKeyword = src.ruleChoiceKeyword; + dst.msgStartIndex = src.msgStartIndex; + dst.expressionStartIndex = src.expressionStartIndex; +} + +function NestedParserState(parser) { + copyNestedParserState(parser, this); +} + +/** + * @constructor + * @private + */ +function MessageFormatParser(text, startIndex, $parse, pluralCat, stringifier, + mustHaveExpression, trustedContext, allOrNothing) { + this.text = text; + this.index = startIndex || 0; + this.$parse = $parse; + this.pluralCat = pluralCat; + this.stringifier = stringifier; + this.mustHaveExpression = !!mustHaveExpression; + this.trustedContext = trustedContext; + this.allOrNothing = !!allOrNothing; + this.expressionFn = null; + this.expressionMinusOffsetFn = null; + this.pluralOffset = null; + this.choices = null; + this.choiceKey = null; + this.interpolationParts = null; + this.msgStartIndex = null; + this.nestedStateStack = []; + this.parsedFn = null; + this.rule = null; + this.ruleStack = null; + this.ruleChoiceKeyword = null; + this.interpNestLevel = null; + this.expressionStartIndex = null; + this.stringStartIndex = null; + this.stringQuote = null; + this.stringInterestsRe = null; + this.angularOperatorStack = null; + this.textPart = null; +} + +// preserve v8 optimization. +var EMPTY_STATE = new NestedParserState(new MessageFormatParser( + /* text= */ '', /* startIndex= */ 0, /* $parse= */ null, /* pluralCat= */ null, /* stringifier= */ null, + /* mustHaveExpression= */ false, /* trustedContext= */ null, /* allOrNothing */ false)); + +MessageFormatParser.prototype.pushState = function pushState() { + this.nestedStateStack.push(new NestedParserState(this)); + copyNestedParserState(EMPTY_STATE, this); +}; + +MessageFormatParser.prototype.popState = function popState() { + if (this.nestedStateStack.length === 0) { + this.errorInParseLogic(); + } + var previousState = this.nestedStateStack.pop(); + copyNestedParserState(previousState, this); +}; + +// Oh my JavaScript! Who knew you couldn't match a regex at a specific +// location in a string but will always search forward?! +// Apparently you'll be growing this ability via the sticky flag (y) in +// ES6. I'll just to work around you for now. +MessageFormatParser.prototype.matchRe = function matchRe(re, search) { + re.lastIndex = this.index; + var match = re.exec(this.text); + if (match != null && (search === true || (match.index == this.index))) { + this.index = re.lastIndex; + return match; + } + return null; +}; + +MessageFormatParser.prototype.searchRe = function searchRe(re) { + return this.matchRe(re, true); +}; + + +MessageFormatParser.prototype.consumeRe = function consumeRe(re) { + // Without the sticky flag, we can't use the .test() method to consume a + // match at the current index. Instead, we'll use the slower .exec() method + // and verify match.index. + return !!this.matchRe(re); +}; + +// Run through our grammar avoiding deeply nested function call chains. +MessageFormatParser.prototype.run = function run(initialRule) { + this.ruleStack = [initialRule]; + do { + this.rule = this.ruleStack.pop(); + while (this.rule) { + this.rule(); + } + this.assertRuleOrNull(this.rule); + } while (this.ruleStack.length > 0); +}; + +MessageFormatParser.prototype.errorInParseLogic = function errorInParseLogic() { + throw $interpolateMinErr('logicbug', + 'The messageformat parser has encountered an internal error. Please file a github issue against the AngularJS project and provide this message text that triggers the bug. Text: “{0}”', + this.text); +}; + +MessageFormatParser.prototype.assertRuleOrNull = function assertRuleOrNull(rule) { + if (rule === void 0) { + this.errorInParseLogic(); + } +}; + +var NEXT_WORD_RE = /\s*(\w+)\s*/g; +MessageFormatParser.prototype.errorExpecting = function errorExpecting() { + // What was wrong with the syntax? Unsupported type, missing comma, or something else? + var match = this.matchRe(NEXT_WORD_RE), position; + if (match == null) { + position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('reqarg', + 'Expected one of “plural” or “select” at line {0}, column {1} of text “{2}”', + position.line, position.column, this.text); + } + var word = match[1]; + if (word == "select" || word == "plural") { + position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('reqcomma', + 'Expected a comma after the keyword “{0}” at line {1}, column {2} of text “{3}”', + word, position.line, position.column, this.text); + } else { + position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('unknarg', + 'Unsupported keyword “{0}” at line {0}, column {1}. Only “plural” and “select” are currently supported. Text: “{3}”', + word, position.line, position.column, this.text); + } +}; + +var STRING_START_RE = /['"]/g; +MessageFormatParser.prototype.ruleString = function ruleString() { + var match = this.matchRe(STRING_START_RE); + if (match == null) { + var position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('wantstring', + 'Expected the beginning of a string at line {0}, column {1} in text “{2}”', + position.line, position.column, this.text); + } + this.startStringAtMatch(match); +}; + +MessageFormatParser.prototype.startStringAtMatch = function startStringAtMatch(match) { + this.stringStartIndex = match.index; + this.stringQuote = match[0]; + this.stringInterestsRe = this.stringQuote == "'" ? SQUOTED_STRING_INTEREST_RE : DQUOTED_STRING_INTEREST_RE; + this.rule = this.ruleInsideString; +}; + +var SQUOTED_STRING_INTEREST_RE = /\\(?:\\|'|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{2}|[0-7]{3}|\r\n|\n|[\s\S])|'/g; +var DQUOTED_STRING_INTEREST_RE = /\\(?:\\|"|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{2}|[0-7]{3}|\r\n|\n|[\s\S])|"/g; +MessageFormatParser.prototype.ruleInsideString = function ruleInsideString() { + var match = this.searchRe(this.stringInterestsRe); + if (match == null) { + var position = indexToLineAndColumn(this.text, this.stringStartIndex); + throw $interpolateMinErr('untermstr', + 'The string beginning at line {0}, column {1} is unterminated in text “{2}”', + position.line, position.column, this.text); + } + var chars = match[0]; + if (match == this.stringQuote) { + this.rule = null; + } +}; + +var PLURAL_OR_SELECT_ARG_TYPE_RE = /\s*(plural|select)\s*,\s*/g; +MessageFormatParser.prototype.rulePluralOrSelect = function rulePluralOrSelect() { + var match = this.searchRe(PLURAL_OR_SELECT_ARG_TYPE_RE); + if (match == null) { + this.errorExpecting(); + } + var argType = match[1]; + switch (argType) { + case "plural": this.rule = this.rulePluralStyle; break; + case "select": this.rule = this.ruleSelectStyle; break; + default: this.errorInParseLogic(); + } +}; + +MessageFormatParser.prototype.rulePluralStyle = function rulePluralStyle() { + this.choices = Object.create(null); + this.ruleChoiceKeyword = this.rulePluralValueOrKeyword; + this.rule = this.rulePluralOffset; +}; + +MessageFormatParser.prototype.ruleSelectStyle = function ruleSelectStyle() { + this.choices = Object.create(null); + this.ruleChoiceKeyword = this.ruleSelectKeyword; + this.rule = this.ruleSelectKeyword; +}; + +var NUMBER_RE = /[0]|(?:[1-9][0-9]*)/g; +var PLURAL_OFFSET_RE = new RegExp("\\s*offset\\s*:\\s*(" + NUMBER_RE.source + ")", "g"); + +MessageFormatParser.prototype.rulePluralOffset = function rulePluralOffset() { + var match = this.matchRe(PLURAL_OFFSET_RE); + this.pluralOffset = (match == null) ? 0 : parseInt(match[1], 10); + this.expressionMinusOffsetFn = subtractOffset(this.expressionFn, this.pluralOffset); + this.rule = this.rulePluralValueOrKeyword; +}; + +MessageFormatParser.prototype.assertChoiceKeyIsNew = function assertChoiceKeyIsNew(choiceKey, index) { + if (this.choices[choiceKey] !== void 0) { + var position = indexToLineAndColumn(this.text, index); + throw $interpolateMinErr('dupvalue', + 'The choice “{0}” is specified more than once. Duplicate key is at line {1}, column {2} in text “{3}”', + choiceKey, position.line, position.column, this.text); + } +}; + +var SELECT_KEYWORD = /\s*(\w+)/g; +MessageFormatParser.prototype.ruleSelectKeyword = function ruleSelectKeyword() { + var match = this.matchRe(SELECT_KEYWORD); + if (match == null) { + this.parsedFn = new SelectMessage(this.expressionFn, this.choices).parsedFn; + this.rule = null; + return; + } + this.choiceKey = match[1]; + this.assertChoiceKeyIsNew(this.choiceKey, match.index); + this.rule = this.ruleMessageText; +}; + +var EXPLICIT_VALUE_OR_KEYWORD_RE = new RegExp("\\s*(?:(?:=(" + NUMBER_RE.source + "))|(\\w+))", "g"); +MessageFormatParser.prototype.rulePluralValueOrKeyword = function rulePluralValueOrKeyword() { + var match = this.matchRe(EXPLICIT_VALUE_OR_KEYWORD_RE); + if (match == null) { + this.parsedFn = new PluralMessage(this.expressionFn, this.choices, this.pluralOffset, this.pluralCat).parsedFn; + this.rule = null; + return; + } + if (match[1] != null) { + this.choiceKey = parseInt(match[1], 10); + } else { + this.choiceKey = match[2]; + } + this.assertChoiceKeyIsNew(this.choiceKey, match.index); + this.rule = this.ruleMessageText; +}; + +var BRACE_OPEN_RE = /\s*{/g; +var BRACE_CLOSE_RE = /}/g; +MessageFormatParser.prototype.ruleMessageText = function ruleMessageText() { + if (!this.consumeRe(BRACE_OPEN_RE)) { + var position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('reqopenbrace', + 'The plural choice “{0}” must be followed by a message in braces at line {1}, column {2} in text “{3}”', + this.choiceKey, position.line, position.column, this.text); + } + this.msgStartIndex = this.index; + this.interpolationParts = new InterpolationParts(this.trustedContext, this.allOrNothing); + this.rule = this.ruleInInterpolationOrMessageText; +}; + +// Note: Since "\" is used as an escape character, don't allow it to be part of the +// startSymbol/endSymbol when I add the feature to allow them to be redefined. +var INTERP_OR_END_MESSAGE_RE = /\\.|{{|}/g; +var INTERP_OR_PLURALVALUE_OR_END_MESSAGE_RE = /\\.|{{|#|}/g; +var ESCAPE_OR_MUSTACHE_BEGIN_RE = /\\.|{{/g; +MessageFormatParser.prototype.advanceInInterpolationOrMessageText = function advanceInInterpolationOrMessageText() { + var currentIndex = this.index, match, re; + if (this.ruleChoiceKeyword == null) { // interpolation + match = this.searchRe(ESCAPE_OR_MUSTACHE_BEGIN_RE); + if (match == null) { // End of interpolation text. Nothing more to process. + this.textPart = this.text.substring(currentIndex); + this.index = this.text.length; + return null; + } + } else { + match = this.searchRe(this.ruleChoiceKeyword == this.rulePluralValueOrKeyword ? + INTERP_OR_PLURALVALUE_OR_END_MESSAGE_RE : INTERP_OR_END_MESSAGE_RE); + if (match == null) { + var position = indexToLineAndColumn(this.text, this.msgStartIndex); + throw $interpolateMinErr('reqendbrace', + 'The plural/select choice “{0}” message starting at line {1}, column {2} does not have an ending closing brace. Text “{3}”', + this.choiceKey, position.line, position.column, this.text); + } + } + // match is non-null. + var token = match[0]; + this.textPart = this.text.substring(currentIndex, match.index); + return token; +}; + +MessageFormatParser.prototype.ruleInInterpolationOrMessageText = function ruleInInterpolationOrMessageText() { + var currentIndex = this.index; + var token = this.advanceInInterpolationOrMessageText(); + if (token == null) { + // End of interpolation text. Nothing more to process. + this.index = this.text.length; + this.interpolationParts.addText(this.text.substring(currentIndex)); + this.rule = null; + return; + } + if (token[0] == "\\") { + // unescape next character and continue + this.interpolationParts.addText(this.textPart + token[1]); + return; + } + this.interpolationParts.addText(this.textPart); + if (token == "{{") { + this.pushState(); + this.ruleStack.push(this.ruleEndMustacheInInterpolationOrMessage); + this.rule = this.ruleEnteredMustache; + } else if (token == "}") { + this.choices[this.choiceKey] = this.interpolationParts.toParsedFn(/*mustHaveExpression=*/false, this.text); + this.rule = this.ruleChoiceKeyword; + } else if (token == "#") { + this.interpolationParts.addExpressionFn(this.expressionMinusOffsetFn); + } else { + this.errorInParseLogic(); + } +}; + +MessageFormatParser.prototype.ruleInterpolate = function ruleInterpolate() { + this.interpolationParts = new InterpolationParts(this.trustedContext, this.allOrNothing); + this.rule = this.ruleInInterpolation; +}; + +MessageFormatParser.prototype.ruleInInterpolation = function ruleInInterpolation() { + var currentIndex = this.index; + var match = this.searchRe(ESCAPE_OR_MUSTACHE_BEGIN_RE); + if (match == null) { + // End of interpolation text. Nothing more to process. + this.index = this.text.length; + this.interpolationParts.addText(this.text.substring(currentIndex)); + this.parsedFn = this.interpolationParts.toParsedFn(this.mustHaveExpression, this.text); + this.rule = null; + return; + } + var token = match[0]; + if (token[0] == "\\") { + // unescape next character and continue + this.interpolationParts.addText(this.text.substring(currentIndex, match.index) + token[1]); + return; + } + this.interpolationParts.addText(this.text.substring(currentIndex, match.index)); + this.pushState(); + this.ruleStack.push(this.ruleInterpolationEndMustache); + this.rule = this.ruleEnteredMustache; +}; + +MessageFormatParser.prototype.ruleInterpolationEndMustache = function ruleInterpolationEndMustache() { + var expressionFn = this.parsedFn; + this.popState(); + this.interpolationParts.addExpressionFn(expressionFn); + this.rule = this.ruleInInterpolation; +}; + +MessageFormatParser.prototype.ruleEnteredMustache = function ruleEnteredMustache() { + this.parsedFn = null; + this.ruleStack.push(this.ruleEndMustache); + this.rule = this.ruleAngularExpression; +}; + +MessageFormatParser.prototype.ruleEndMustacheInInterpolationOrMessage = function ruleEndMustacheInInterpolationOrMessage() { + var expressionFn = this.parsedFn; + this.popState(); + this.interpolationParts.addExpressionFn(expressionFn); + this.rule = this.ruleInInterpolationOrMessageText; +}; + + + +var INTERP_END_RE = /\s*}}/g; +MessageFormatParser.prototype.ruleEndMustache = function ruleEndMustache() { + var match = this.matchRe(INTERP_END_RE); + if (match == null) { + var position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('reqendinterp', + 'Expecting end of interpolation symbol, “{0}”, at line {1}, column {2} in text “{3}”', + '}}', position.line, position.column, this.text); + } + if (this.parsedFn == null) { + // If we parsed a MessageFormat extension, (e.g. select/plural today, maybe more some other + // day), then the result *has* to be a string and those rules would have already set + // this.parsedFn. If there was no MessageFormat extension, then there is no requirement to + // stringify the result and parsedFn isn't set. We set it here. While we could have set it + // unconditionally when exiting the Angular expression, I intend for us to not just replace + // $interpolate, but also to replace $parse in a future version (so ng-bind can work), and in + // such a case we do not want to unnecessarily stringify something if it's not going to be used + // in a string context. + this.parsedFn = this.$parse(this.expressionFn, this.stringifier); + this.parsedFn['exp'] = this.expressionFn['exp']; // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js + this.parsedFn['expressions'] = this.expressionFn['expressions']; // Require this to call $compile.$$addBindingInfo() which allows Protractor to find elements by binding. + } + this.rule = null; +}; + +MessageFormatParser.prototype.ruleAngularExpression = function ruleAngularExpression() { + this.angularOperatorStack = []; + this.expressionStartIndex = this.index; + this.rule = this.ruleInAngularExpression; +}; + +function getEndOperator(opBegin) { + switch (opBegin) { + case "{": return "}"; + case "[": return "]"; + case "(": return ")"; + default: return null; + } +} + +function getBeginOperator(opEnd) { + switch (opEnd) { + case "}": return "{"; + case "]": return "["; + case ")": return "("; + default: return null; + } +} + +// TODO(chirayu): The interpolation endSymbol must also be accounted for. It +// just so happens that "}" is an operator so it's in the list below. But we +// should support any other type of start/end interpolation symbol. +var INTERESTING_OPERATORS_RE = /[[\]{}()'",]/g; +MessageFormatParser.prototype.ruleInAngularExpression = function ruleInAngularExpression() { + var startIndex = this.index; + var match = this.searchRe(INTERESTING_OPERATORS_RE); + var position; + if (match == null) { + if (this.angularOperatorStack.length === 0) { + // This is the end of the Angular expression so this is actually a + // success. Note that when inside an interpolation, this means we even + // consumed the closing interpolation symbols if they were curlies. This + // is NOT an error at this point but will become an error further up the + // stack when the part that saw the opening curlies is unable to find the + // closing ones. + this.index = this.text.length; + this.expressionFn = this.$parse(this.text.substring(this.expressionStartIndex, this.index)); + // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js + this.expressionFn['exp'] = this.text.substring(this.expressionStartIndex, this.index); + this.expressionFn['expressions'] = this.expressionFn['expressions']; + this.rule = null; + return; + } + var innermostOperator = this.angularOperatorStack[0]; + throw $interpolateMinErr('badexpr', + 'Unexpected end of Angular expression. Expecting operator “{0}” at the end of the text “{1}”', + this.getEndOperator(innermostOperator), this.text); + } + var operator = match[0]; + if (operator == "'" || operator == '"') { + this.ruleStack.push(this.ruleInAngularExpression); + this.startStringAtMatch(match); + return; + } + if (operator == ",") { + if (this.trustedContext) { + position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('unsafe', + 'Use of select/plural MessageFormat syntax is currently disallowed in a secure context ({0}). At line {1}, column {2} of text “{3}”', + this.trustedContext, position.line, position.column, this.text); + } + // only the top level comma has relevance. + if (this.angularOperatorStack.length === 0) { + // todo: does this need to be trimmed? + this.expressionFn = this.$parse(this.text.substring(this.expressionStartIndex, match.index)); + // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js + this.expressionFn['exp'] = this.text.substring(this.expressionStartIndex, match.index); + this.expressionFn['expressions'] = this.expressionFn['expressions']; + this.rule = null; + this.rule = this.rulePluralOrSelect; + } + return; + } + if (getEndOperator(operator) != null) { + this.angularOperatorStack.unshift(operator); + return; + } + var beginOperator = getBeginOperator(operator); + if (beginOperator == null) { + this.errorInParseLogic(); + } + if (this.angularOperatorStack.length > 0) { + if (beginOperator == this.angularOperatorStack[0]) { + this.angularOperatorStack.shift(); + return; + } + position = indexToLineAndColumn(this.text, this.index); + throw $interpolateMinErr('badexpr', + 'Unexpected operator “{0}” at line {1}, column {2} in text. Was expecting “{3}”. Text: “{4}”', + operator, position.line, position.column, getEndOperator(this.angularOperatorStack[0]), this.text); + } + // We are trying to pop off the operator stack but there really isn't anything to pop off. + this.index = match.index; + this.expressionFn = this.$parse(this.text.substring(this.expressionStartIndex, this.index)); + // Needed to pretend to be $interpolate for tests copied from interpolateSpec.js + this.expressionFn['exp'] = this.text.substring(this.expressionStartIndex, this.index); + this.expressionFn['expressions'] = this.expressionFn['expressions']; + this.rule = null; +}; + +// NOTE: ADVANCED_OPTIMIZATIONS mode. +// +// This file is compiled with Closure compiler's ADVANCED_OPTIMIZATIONS flag! Be wary of using +// constructs incompatible with that mode. + +/* global $interpolateMinErr: true */ +/* global isFunction: true */ +/* global noop: true */ +/* global toJson: true */ +/* global MessageFormatParser: false */ +/* global stringify: false */ + +/** + * @ngdoc module + * @name ngMessageFormat + * @packageName angular-message-format + * + * @description + * + * ## What is ngMessageFormat? + * + * The ngMessageFormat module extends the Angular {@link ng.$interpolate `$interpolate`} service + * with a syntax for handling pluralization and gender specific messages, which is based on the + * [ICU MessageFormat syntax][ICU]. + * + * See [the design doc][ngMessageFormat doc] for more information. + * + * [ICU]: http://userguide.icu-project.org/formatparse/messages#TOC-MessageFormat + * [ngMessageFormat doc]: https://docs.google.com/a/google.com/document/d/1pbtW2yvtmFBikfRrJd8VAsabiFkKezmYZ_PbgdjQOVU/edit + * + * ## Examples + * + * ### Gender + * + * This example uses the "select" keyword to specify the message based on gender. + * + * + * + *
    + * Select Recipient:
    + +

    {{recipient.gender, select, + male {{{recipient.name}} unwrapped his gift. } + female {{{recipient.name}} unwrapped her gift. } + other {{{recipient.name}} unwrapped their gift. } + }}

    + *
    + *
    + * + * function Person(name, gender) { + * this.name = name; + * this.gender = gender; + * } + * + * var alice = new Person("Alice", "female"), + * bob = new Person("Bob", "male"), + * ashley = new Person("Ashley", ""); + * + * angular.module('msgFmtExample', ['ngMessageFormat']) + * .controller('AppController', ['$scope', function($scope) { + * $scope.recipients = [alice, bob, ashley]; + * $scope.recipient = $scope.recipients[0]; + * }]); + * + *
    + * + * ### Plural + * + * This example shows how the "plural" keyword is used to account for a variable number of entities. + * The "#" variable holds the current number and can be embedded in the message. + * + * Note that "=1" takes precedence over "one". + * + * The example also shows the "offset" keyword, which allows you to offset the value of the "#" variable. + * + * + * + *
    + *
    + * Select recipients:
    + *
    + *

    {{recipients.length, plural, offset:1 + * =0 {{{sender.name}} gave no gifts (\#=#)} + * =1 {{{sender.name}} gave a gift to {{recipients[0].name}} (\#=#)} + * one {{{sender.name}} gave {{recipients[0].name}} and one other person a gift (\#=#)} + * other {{{sender.name}} gave {{recipients[0].name}} and # other people a gift (\#=#)} + * }}

    + *
    + *
    + * + * + * function Person(name, gender) { + * this.name = name; + * this.gender = gender; + * } + * + * var alice = new Person("Alice", "female"), + * bob = new Person("Bob", "male"), + * sarah = new Person("Sarah", "female"), + * harry = new Person("Harry Potter", "male"), + * ashley = new Person("Ashley", ""); + * + * angular.module('msgFmtExample', ['ngMessageFormat']) + * .controller('AppController', ['$scope', function($scope) { + * $scope.people = [alice, bob, sarah, ashley]; + * $scope.recipients = [alice, bob, sarah]; + * $scope.sender = harry; + * }]); + * + * + * + * describe('MessageFormat plural', function() { + * + * it('should pluralize initial values', function() { + * var messageElem = element(by.binding('recipients.length')), + * decreaseRecipientsBtn = element(by.id('decreaseRecipients')); + * + * expect(messageElem.getText()).toEqual('Harry Potter gave Alice and 2 other people a gift (#=2)'); + * decreaseRecipientsBtn.click(); + * expect(messageElem.getText()).toEqual('Harry Potter gave Alice and one other person a gift (#=1)'); + * decreaseRecipientsBtn.click(); + * expect(messageElem.getText()).toEqual('Harry Potter gave a gift to Alice (#=0)'); + * decreaseRecipientsBtn.click(); + * expect(messageElem.getText()).toEqual('Harry Potter gave no gifts (#=-1)'); + * }); + * }); + * + *
    + * + * ### Plural and Gender together + * + * This example shows how you can specify gender rules for specific plural matches - in this case, + * =1 is special cased for gender. + * + * + *
    + Select recipients:
    +
    +

    {{recipients.length, plural, + =0 {{{sender.name}} has not given any gifts to anyone.} + =1 { {{recipients[0].gender, select, + female { {{sender.name}} gave {{recipients[0].name}} her gift.} + male { {{sender.name}} gave {{recipients[0].name}} his gift.} + other { {{sender.name}} gave {{recipients[0].name}} their gift.} + }} + } + other {{{sender.name}} gave {{recipients.length}} people gifts.} + }}

    + + * + * function Person(name, gender) { + * this.name = name; + * this.gender = gender; + * } + * + * var alice = new Person("Alice", "female"), + * bob = new Person("Bob", "male"), + * harry = new Person("Harry Potter", "male"), + * ashley = new Person("Ashley", ""); + * + * angular.module('msgFmtExample', ['ngMessageFormat']) + * .controller('AppController', ['$scope', function($scope) { + * $scope.people = [alice, bob, ashley]; + * $scope.recipients = [alice]; + * $scope.sender = harry; + * }]); + * + + */ + +var $$MessageFormatFactory = ['$parse', '$locale', '$sce', '$exceptionHandler', function $$messageFormat( + $parse, $locale, $sce, $exceptionHandler) { + + function getStringifier(trustedContext, allOrNothing, text) { + return function stringifier(value) { + try { + value = trustedContext ? $sce['getTrusted'](trustedContext, value) : $sce['valueOf'](value); + return allOrNothing && (value === void 0) ? value : stringify(value); + } catch (err) { + $exceptionHandler($interpolateMinErr['interr'](text, err)); + } + }; + } + + function interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { + var stringifier = getStringifier(trustedContext, allOrNothing, text); + var parser = new MessageFormatParser(text, 0, $parse, $locale['pluralCat'], stringifier, + mustHaveExpression, trustedContext, allOrNothing); + parser.run(parser.ruleInterpolate); + return parser.parsedFn; + } + + return { + 'interpolate': interpolate + }; +}]; + +var $$interpolateDecorator = ['$$messageFormat', '$delegate', function $$interpolateDecorator($$messageFormat, $interpolate) { + if ($interpolate['startSymbol']() != "{{" || $interpolate['endSymbol']() != "}}") { + throw $interpolateMinErr('nochgmustache', 'angular-message-format.js currently does not allow you to use custom start and end symbols for interpolation.'); + } + var interpolate = $$messageFormat['interpolate']; + interpolate['startSymbol'] = $interpolate['startSymbol']; + interpolate['endSymbol'] = $interpolate['endSymbol']; + return interpolate; +}]; + +var $interpolateMinErr; +var isFunction; +var noop; +var toJson; + +var module = window['angular']['module']('ngMessageFormat', ['ng']); +module['factory']('$$messageFormat', $$MessageFormatFactory); +module['config'](['$provide', function($provide) { + $interpolateMinErr = window['angular']['$interpolateMinErr']; + isFunction = window['angular']['isFunction']; + noop = window['angular']['noop']; + toJson = window['angular']['toJson']; + + $provide['decorator']('$interpolate', $$interpolateDecorator); +}]); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-message-format.min.js b/src/main/resources/static/module/angular/angular-message-format.min.js new file mode 100644 index 0000000..9ff8322 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-message-format.min.js @@ -0,0 +1,26 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(l){'use strict';function D(a){if(null==a)return"";switch(typeof a){case "string":return a;case "number":return""+a;default:return v(a)}}function f(a,b){for(var d=a.split(/\n/g),k=0;k=c.length)b-=c.length;else return{h:k+1,f:b+1}}}function w(a){function b(){return a}var d=x[a];if(null!=d)return d;b.$$watchDelegate=function(b,d,c){var e=b.$watch(q,function(){m(d)&&d.call(null,a,a,b);e()},c);return e};x[a]=b;b.exp=a;b.expressions=[];return b}function F(a,b){function d(a){return void 0== +a?a:a-b}function c(b){return d(a(b))}if(0===b)return a;var e;c.$$watchDelegate=function(b,c,k){return e=b.$watch(a,function(a,k){m(c)&&c.call(null,d(a),d(k),b)},k)};return c}function h(a,b){var d=this;this.b=a;this.e=b;if(void 0===b.other)throw e("reqother");this.d=function(a){return d.D(a)};this.d.$$watchDelegate=function(a,b,c){return d.P(a,b,c)};this.d.exp=a.exp;this.d.expressions=a.expressions}function p(a,b,d,c){var e=this;this.scope=b;this.oa=a;this.v=d;this.qa=c;this.U=void 0;this.K=q;this.ka= +b.$watch(a.b,function(a){return e.ja(a)},c)}function r(a,b){h.call(this,a,b)}function y(){}function s(a,b,d,c){h.call(this,a,b);this.offset=d;this.M=c}function z(){}function g(a,b){this.u=a;this.B=b;this.i=[];this.g=[];this.J=[];this.s="";this.q=null}function t(a,b,d){this.c=a;this.scope=b;this.W=void 0;this.v=d;var c=this;this.la=b.$watchGroup(a.g,function(a,b){c.Ea(a,b)})}function u(a,b){b.b=a.b;b.C=a.C;b.w=a.w;b.e=a.e;b.k=a.k;b.c=a.c;b.n=a.n;b.F=a.F;b.l=a.l}function A(a){u(a,this)}function c(a, +b,d,c,e,E,f,g){this.text=a;this.index=b||0;this.A=d;this.M=c;this.Da=e;this.pa=!!E;this.u=f;this.B=!!g;this.F=this.c=this.k=this.e=this.w=this.C=this.b=null;this.L=[];this.G=this.j=this.ca=this.O=this.da=this.l=this.n=this.o=this.a=this.d=null}function B(a){switch(a){case "{":return"}";case "[":return"]";case "(":return")";default:return null}}function G(a){switch(a){case "}":return"{";case "]":return"[";case ")":return"(";default:return null}}var x=Object.create(null);h.prototype.T=function(a){return this.e[this.R(a)]}; +h.prototype.D=function(a){return this.T(this.b(a))(a)};h.prototype.P=function(a,b,d){var c=new p(this,a,b,d);return function(){c.I()}};p.prototype.ja=function(a){var b=this;this.K();a=this.oa.T(a);this.K=this.scope.$watch(a,function(a,c){return b.na(a,c)},this.qa)};p.prototype.na=function(a,b){m(this.v)&&this.v.call(null,a,a===b?a:this.U,this.scope);this.U=a};p.prototype.I=function(){this.ka();this.K()};y.prototype=h.prototype;r.prototype=new y;r.prototype.R=function(a){return void 0!==this.e[a]? +a:"other"};z.prototype=h.prototype;s.prototype=new z;s.prototype.R=function(a){if(isNaN(a))return"other";if(void 0!==this.e[a])return a;a=this.M(a-this.offset);return void 0!==this.e[a]?a:"other"};g.prototype.S=function(){this.s&&(null==this.q?this.i.push(this.s):(this.i.push(this.q.join("")),this.q=null),this.s="")};g.prototype.p=function(a){a.length&&(this.s?this.q?this.q.push(a):this.q=[this.s,a]:this.s=a)};g.prototype.H=function(a){this.S();this.J.push(this.i.length);this.g.push(a);this.i.push("")}; +g.prototype.ma=function(a){for(var b=Array(this.g.length),d=0;d + * + *
    + *
    Please enter a value for this field.
    + *
    This field must be a valid email address.
    + *
    This field can be at most 15 characters long.
    + *
    + * + * ``` + * + * In order to show error messages corresponding to `myField` we first create an element with an `ngMessages` attribute + * set to the `$error` object owned by the `myField` input in our `myForm` form. + * + * Within this element we then create separate elements for each of the possible errors that `myField` could have. + * The `ngMessage` attribute is used to declare which element(s) will appear for which error - for example, + * setting `ng-message="required"` specifies that this particular element should be displayed when there + * is no value present for the required field `myField` (because the key `required` will be `true` in the object + * `myForm.myField.$error`). + * + * ### Message order + * + * By default, `ngMessages` will only display one message for a particular key/value collection at any time. If more + * than one message (or error) key is currently true, then which message is shown is determined by the order of messages + * in the HTML template code (messages declared first are prioritised). This mechanism means the developer does not have + * to prioritise messages using custom JavaScript code. + * + * Given the following error object for our example (which informs us that the field `myField` currently has both the + * `required` and `email` errors): + * + * ```javascript + * + * myField.$error = { required : true, email: true, maxlength: false }; + * ``` + * The `required` message will be displayed to the user since it appears before the `email` message in the DOM. + * Once the user types a single character, the `required` message will disappear (since the field now has a value) + * but the `email` message will be visible because it is still applicable. + * + * ### Displaying multiple messages at the same time + * + * While `ngMessages` will by default only display one error element at a time, the `ng-messages-multiple` attribute can + * be applied to the `ngMessages` container element to cause it to display all applicable error messages at once: + * + * ```html + * + *
    ...
    + * + * + * ... + * ``` + * + * ## Reusing and Overriding Messages + * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline + * template. This allows for generic collection of messages to be reused across multiple parts of an + * application. + * + * ```html + * + * + *
    + *
    + *
    + * ``` + * + * However, including generic messages may not be useful enough to match all input fields, therefore, + * `ngMessages` provides the ability to override messages defined in the remote template by redefining + * them within the directive container. + * + * ```html + * + * + * + *
    + * + * + *
    + * + *
    You did not enter your email address
    + * + * + *
    Your email address is invalid
    + * + * + *
    + *
    + *
    + * ``` + * + * In the example HTML code above the message that is set on required will override the corresponding + * required message defined within the remote template. Therefore, with particular input fields (such + * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied + * while more generic messages can be used to handle other, more general input errors. + * + * ## Dynamic Messaging + * ngMessages also supports using expressions to dynamically change key values. Using arrays and + * repeaters to list messages is also supported. This means that the code below will be able to + * fully adapt itself and display the appropriate message when any of the expression data changes: + * + * ```html + *
    + * + *
    + *
    You did not enter your email address
    + *
    + * + *
    {{ errorMessage.text }}
    + *
    + *
    + *
    + * ``` + * + * The `errorMessage.type` expression can be a string value or it can be an array so + * that multiple errors can be associated with a single error message: + * + * ```html + * + *
    + *
    You did not enter your email address
    + *
    + * Your email must be between 5 and 100 characters long + *
    + *
    + * ``` + * + * Feel free to use other structural directives such as ng-if and ng-switch to further control + * what messages are active and when. Be careful, if you place ng-message on the same element + * as these structural directives, Angular may not be able to determine if a message is active + * or not. Therefore it is best to place the ng-message on a child element of the structural + * directive. + * + * ```html + *
    + *
    + *
    Please enter something
    + *
    + *
    + * ``` + * + * ## Animations + * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and + * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from + * the DOM by the `ngMessages` directive. + * + * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS + * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no + * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can + * hook into the animations whenever these classes are added/removed. + * + * Let's say that our HTML code for our messages container looks like so: + * + * ```html + * + * ``` + * + * Then the CSS animation code for the message container looks like so: + * + * ```css + * .my-messages { + * transition:1s linear all; + * } + * .my-messages.ng-active { + * // messages are visible + * } + * .my-messages.ng-inactive { + * // messages are hidden + * } + * ``` + * + * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter + * and leave animation is triggered for each particular element bound to the `ngMessage` directive. + * + * Therefore, the CSS code for the inner messages looks like so: + * + * ```css + * .some-message { + * transition:1s linear all; + * } + * + * .some-message.ng-enter {} + * .some-message.ng-enter.ng-enter-active {} + * + * .some-message.ng-leave {} + * .some-message.ng-leave.ng-leave-active {} + * ``` + * + * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate. + */ +angular.module('ngMessages', [], function initAngularHelpers() { + // Access helpers from angular core. + // Do it inside a `config` block to ensure `window.angular` is available. + forEach = angular.forEach; + isArray = angular.isArray; + isString = angular.isString; + jqLite = angular.element; +}) + + /** + * @ngdoc directive + * @module ngMessages + * @name ngMessages + * @restrict AE + * + * @description + * `ngMessages` is a directive that is designed to show and hide messages based on the state + * of a key/value object that it listens on. The directive itself complements error message + * reporting with the `ngModel` $error object (which stores a key/value state of validation errors). + * + * `ngMessages` manages the state of internal messages within its container element. The internal + * messages use the `ngMessage` directive and will be inserted/removed from the page depending + * on if they're present within the key/value object. By default, only one message will be displayed + * at a time and this depends on the prioritization of the messages within the template. (This can + * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.) + * + * A remote template can also be used to promote message reusability and messages can also be + * overridden. + * + * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. + * + * @usage + * ```html + * + * + * ... + * ... + * ... + * + * + * + * + * ... + * ... + * ... + * + * ``` + * + * @param {string} ngMessages an angular expression evaluating to a key/value object + * (this is typically the $error object on an ngModel instance). + * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true + * + * @example + * + * + *
    + * + *
    myForm.myName.$error = {{ myForm.myName.$error | json }}
    + * + *
    + *
    You did not enter a field
    + *
    Your field is too short
    + *
    Your field is too long
    + *
    + *
    + *
    + * + * angular.module('ngMessagesExample', ['ngMessages']); + * + *
    + */ + .directive('ngMessages', ['$animate', function($animate) { + var ACTIVE_CLASS = 'ng-active'; + var INACTIVE_CLASS = 'ng-inactive'; + + return { + require: 'ngMessages', + restrict: 'AE', + controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { + var ctrl = this; + var latestKey = 0; + var nextAttachId = 0; + + this.getAttachId = function getAttachId() { return nextAttachId++; }; + + var messages = this.messages = {}; + var renderLater, cachedCollection; + + this.render = function(collection) { + collection = collection || {}; + + renderLater = false; + cachedCollection = collection; + + // this is true if the attribute is empty or if the attribute value is truthy + var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) || + isAttrTruthy($scope, $attrs.multiple); + + var unmatchedMessages = []; + var matchedKeys = {}; + var messageItem = ctrl.head; + var messageFound = false; + var totalMessages = 0; + + // we use != instead of !== to allow for both undefined and null values + while (messageItem != null) { + totalMessages++; + var messageCtrl = messageItem.message; + + var messageUsed = false; + if (!messageFound) { + forEach(collection, function(value, key) { + if (!messageUsed && truthy(value) && messageCtrl.test(key)) { + // this is to prevent the same error name from showing up twice + if (matchedKeys[key]) return; + matchedKeys[key] = true; + + messageUsed = true; + messageCtrl.attach(); + } + }); + } + + if (messageUsed) { + // unless we want to display multiple messages then we should + // set a flag here to avoid displaying the next message in the list + messageFound = !multiple; + } else { + unmatchedMessages.push(messageCtrl); + } + + messageItem = messageItem.next; + } + + forEach(unmatchedMessages, function(messageCtrl) { + messageCtrl.detach(); + }); + + unmatchedMessages.length !== totalMessages + ? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS) + : $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS); + }; + + $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render); + + // If the element is destroyed, proactively destroy all the currently visible messages + $element.on('$destroy', function() { + forEach(messages, function(item) { + item.message.detach(); + }); + }); + + this.reRender = function() { + if (!renderLater) { + renderLater = true; + $scope.$evalAsync(function() { + if (renderLater) { + cachedCollection && ctrl.render(cachedCollection); + } + }); + } + }; + + this.register = function(comment, messageCtrl) { + var nextKey = latestKey.toString(); + messages[nextKey] = { + message: messageCtrl + }; + insertMessageNode($element[0], comment, nextKey); + comment.$$ngMessageNode = nextKey; + latestKey++; + + ctrl.reRender(); + }; + + this.deregister = function(comment) { + var key = comment.$$ngMessageNode; + delete comment.$$ngMessageNode; + removeMessageNode($element[0], comment, key); + delete messages[key]; + ctrl.reRender(); + }; + + function findPreviousMessage(parent, comment) { + var prevNode = comment; + var parentLookup = []; + + while (prevNode && prevNode !== parent) { + var prevKey = prevNode.$$ngMessageNode; + if (prevKey && prevKey.length) { + return messages[prevKey]; + } + + // dive deeper into the DOM and examine its children for any ngMessage + // comments that may be in an element that appears deeper in the list + if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) === -1) { + parentLookup.push(prevNode); + prevNode = prevNode.childNodes[prevNode.childNodes.length - 1]; + } else if (prevNode.previousSibling) { + prevNode = prevNode.previousSibling; + } else { + prevNode = prevNode.parentNode; + parentLookup.push(prevNode); + } + } + } + + function insertMessageNode(parent, comment, key) { + var messageNode = messages[key]; + if (!ctrl.head) { + ctrl.head = messageNode; + } else { + var match = findPreviousMessage(parent, comment); + if (match) { + messageNode.next = match.next; + match.next = messageNode; + } else { + messageNode.next = ctrl.head; + ctrl.head = messageNode; + } + } + } + + function removeMessageNode(parent, comment, key) { + var messageNode = messages[key]; + + var match = findPreviousMessage(parent, comment); + if (match) { + match.next = messageNode.next; + } else { + ctrl.head = messageNode.next; + } + } + }] + }; + + function isAttrTruthy(scope, attr) { + return (isString(attr) && attr.length === 0) || //empty attribute + truthy(scope.$eval(attr)); + } + + function truthy(val) { + return isString(val) ? val.length : !!val; + } + }]) + + /** + * @ngdoc directive + * @name ngMessagesInclude + * @restrict AE + * @scope + * + * @description + * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template + * code from a remote template and place the downloaded template code into the exact spot + * that the ngMessagesInclude directive is placed within the ngMessages container. This allows + * for a series of pre-defined messages to be reused and also allows for the developer to + * determine what messages are overridden due to the placement of the ngMessagesInclude directive. + * + * @usage + * ```html + * + * + * ... + * + * + * + * + * ... + * + * ``` + * + * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. + * + * @param {string} ngMessagesInclude|src a string value corresponding to the remote template. + */ + .directive('ngMessagesInclude', + ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) { + + return { + restrict: 'AE', + require: '^^ngMessages', // we only require this for validation sake + link: function($scope, element, attrs) { + var src = attrs.ngMessagesInclude || attrs.src; + $templateRequest(src).then(function(html) { + if ($scope.$$destroyed) return; + + if (isString(html) && !html.trim()) { + // Empty template - nothing to compile + replaceElementWithMarker(element, src); + } else { + // Non-empty template - compile and link + $compile(html)($scope, function(contents) { + element.after(contents); + replaceElementWithMarker(element, src); + }); + } + }); + } + }; + + // Helpers + function replaceElementWithMarker(element, src) { + // A comment marker is placed for debugging purposes + var comment = $compile.$$createComment ? + $compile.$$createComment('ngMessagesInclude', src) : + $document[0].createComment(' ngMessagesInclude: ' + src + ' '); + var marker = jqLite(comment); + element.after(marker); + + // Don't pollute the DOM anymore by keeping an empty directive element + element.remove(); + } + }]) + + /** + * @ngdoc directive + * @name ngMessage + * @restrict AE + * @scope + * + * @description + * `ngMessage` is a directive with the purpose to show and hide a particular message. + * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element + * must be situated since it determines which messages are visible based on the state + * of the provided key/value map that `ngMessages` listens on. + * + * More information about using `ngMessage` can be found in the + * {@link module:ngMessages `ngMessages` module documentation}. + * + * @usage + * ```html + * + * + * ... + * ... + * + * + * + * + * ... + * ... + * + * ``` + * + * @param {expression} ngMessage|when a string value corresponding to the message key. + */ + .directive('ngMessage', ngMessageDirectiveFactory()) + + + /** + * @ngdoc directive + * @name ngMessageExp + * @restrict AE + * @priority 1 + * @scope + * + * @description + * `ngMessageExp` is a directive with the purpose to show and hide a particular message. + * For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element + * must be situated since it determines which messages are visible based on the state + * of the provided key/value map that `ngMessages` listens on. + * + * @usage + * ```html + * + * + * ... + * + * + * + * + * ... + * + * ``` + * + * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. + * + * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key. + */ + .directive('ngMessageExp', ngMessageDirectiveFactory()); + +function ngMessageDirectiveFactory() { + return ['$animate', function($animate) { + return { + restrict: 'AE', + transclude: 'element', + priority: 1, // must run before ngBind, otherwise the text is set on the comment + terminal: true, + require: '^^ngMessages', + link: function(scope, element, attrs, ngMessagesCtrl, $transclude) { + var commentNode = element[0]; + + var records; + var staticExp = attrs.ngMessage || attrs.when; + var dynamicExp = attrs.ngMessageExp || attrs.whenExp; + var assignRecords = function(items) { + records = items + ? (isArray(items) + ? items + : items.split(/[\s,]+/)) + : null; + ngMessagesCtrl.reRender(); + }; + + if (dynamicExp) { + assignRecords(scope.$eval(dynamicExp)); + scope.$watchCollection(dynamicExp, assignRecords); + } else { + assignRecords(staticExp); + } + + var currentElement, messageCtrl; + ngMessagesCtrl.register(commentNode, messageCtrl = { + test: function(name) { + return contains(records, name); + }, + attach: function() { + if (!currentElement) { + $transclude(function(elm, newScope) { + $animate.enter(elm, null, element); + currentElement = elm; + + // Each time we attach this node to a message we get a new id that we can match + // when we are destroying the node later. + var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId(); + + // in the event that the element or a parent element is destroyed + // by another structural directive then it's time + // to deregister the message from the controller + currentElement.on('$destroy', function() { + if (currentElement && currentElement.$$attachId === $$attachId) { + ngMessagesCtrl.deregister(commentNode); + messageCtrl.detach(); + } + newScope.$destroy(); + }); + }); + } + }, + detach: function() { + if (currentElement) { + var elm = currentElement; + currentElement = null; + $animate.leave(elm); + } + } + }); + } + }; + }]; + + function contains(collection, key) { + if (collection) { + return isArray(collection) + ? collection.indexOf(key) >= 0 + : collection.hasOwnProperty(key); + } + } +} + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-messages.min.js b/src/main/resources/static/module/angular/angular-messages.min.js new file mode 100644 index 0000000..b898376 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-messages.min.js @@ -0,0 +1,12 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(y,l){'use strict';function w(){return["$animate",function(t){return{restrict:"AE",transclude:"element",priority:1,terminal:!0,require:"^^ngMessages",link:function(u,n,a,c,f){var e=n[0],d,r=a.ngMessage||a.when;a=a.ngMessageExp||a.whenExp;var k=function(a){d=a?p(a)?a:a.split(/[\s,]+/):null;c.reRender()};a?(k(u.$eval(a)),u.$watchCollection(a,k)):k(r);var g,s;c.register(e,s={test:function(a){var m=d;a=m?p(m)?0<=m.indexOf(a):m.hasOwnProperty(a):void 0;return a},attach:function(){g||f(function(a, +m){t.enter(a,null,n);g=a;var d=g.$$attachId=c.getAttachId();g.on("$destroy",function(){g&&g.$$attachId===d&&(c.deregister(e),s.detach());m.$destroy()})})},detach:function(){if(g){var a=g;g=null;t.leave(a)}}})}}}]}var v,p,q,x;l.module("ngMessages",[],function(){v=l.forEach;p=l.isArray;q=l.isString;x=l.element}).directive("ngMessages",["$animate",function(t){function u(a,c){return q(c)&&0===c.length||n(a.$eval(c))}function n(a){return q(a)?a.length:!!a}return{require:"ngMessages",restrict:"AE",controller:["$element", +"$scope","$attrs",function(a,c,f){function e(a,c){for(var b=c,d=[];b&&b!==a;){var h=b.$$ngMessageNode;if(h&&h.length)return g[h];b.childNodes.length&&-1===d.indexOf(b)?(d.push(b),b=b.childNodes[b.childNodes.length-1]):b.previousSibling?b=b.previousSibling:(b=b.parentNode,d.push(b))}}var d=this,r=0,k=0;this.getAttachId=function(){return k++};var g=this.messages={},s,l;this.render=function(m){m=m||{};s=!1;l=m;for(var g=u(c,f.ngMessagesMultiple)||u(c,f.multiple),b=[],e={},h=d.head,r=!1,k=0;null!=h;){k++; +var q=h.message,p=!1;r||v(m,function(a,b){!p&&n(a)&&q.test(b)&&!e[b]&&(p=e[b]=!0,q.attach())});p?r=!g:b.push(q);h=h.next}v(b,function(a){a.detach()});b.length!==k?t.setClass(a,"ng-active","ng-inactive"):t.setClass(a,"ng-inactive","ng-active")};c.$watchCollection(f.ngMessages||f["for"],d.render);a.on("$destroy",function(){v(g,function(a){a.message.detach()})});this.reRender=function(){s||(s=!0,c.$evalAsync(function(){s&&l&&d.render(l)}))};this.register=function(c,f){var b=r.toString();g[b]={message:f}; +var k=a[0],h=g[b];d.head?(k=e(k,c))?(h.next=k.next,k.next=h):(h.next=d.head,d.head=h):d.head=h;c.$$ngMessageNode=b;r++;d.reRender()};this.deregister=function(c){var f=c.$$ngMessageNode;delete c.$$ngMessageNode;var b=g[f];(c=e(a[0],c))?c.next=b.next:d.head=b.next;delete g[f];d.reRender()}}]}}]).directive("ngMessagesInclude",["$templateRequest","$document","$compile",function(l,p,n){function a(a,f){var e=n.$$createComment?n.$$createComment("ngMessagesInclude",f):p[0].createComment(" ngMessagesInclude: "+ +f+" "),e=x(e);a.after(e);a.remove()}return{restrict:"AE",require:"^^ngMessages",link:function(c,f,e){var d=e.ngMessagesInclude||e.src;l(d).then(function(e){c.$$destroyed||(q(e)&&!e.trim()?a(f,d):n(e)(c,function(c){f.after(c);a(f,d)}))})}}}]).directive("ngMessage",w()).directive("ngMessageExp",w())})(window,window.angular); +//# sourceMappingURL=angular-messages.min.js.map diff --git a/src/main/resources/static/module/angular/angular-messages.min.js.map b/src/main/resources/static/module/angular/angular-messages.min.js.map new file mode 100644 index 0000000..b92138e --- /dev/null +++ b/src/main/resources/static/module/angular/angular-messages.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-messages.min.js", +"lineCount":11, +"mappings":"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", +"sources":["angular-messages.js"], +"names":["window","angular","ngMessageDirectiveFactory","$animate","restrict","transclude","priority","terminal","require","link","scope","element","attrs","ngMessagesCtrl","$transclude","commentNode","records","staticExp","ngMessage","when","dynamicExp","ngMessageExp","whenExp","assignRecords","items","isArray","split","reRender","$eval","$watchCollection","currentElement","messageCtrl","register","test","name","collection","indexOf","hasOwnProperty","attach","elm","newScope","enter","$$attachId","getAttachId","on","deregister","detach","$destroy","leave","forEach","isString","jqLite","module","initAngularHelpers","directive","isAttrTruthy","attr","length","truthy","val","controller","$element","$scope","$attrs","findPreviousMessage","parent","comment","prevNode","parentLookup","prevKey","$$ngMessageNode","messages","childNodes","push","previousSibling","parentNode","ctrl","latestKey","nextAttachId","this.getAttachId","renderLater","cachedCollection","render","this.render","multiple","ngMessagesMultiple","unmatchedMessages","matchedKeys","messageItem","head","messageFound","totalMessages","message","messageUsed","value","key","next","setClass","ACTIVE_CLASS","INACTIVE_CLASS","ngMessages","item","this.reRender","$evalAsync","this.register","nextKey","toString","messageNode","match","this.deregister","$templateRequest","$document","$compile","replaceElementWithMarker","src","$$createComment","createComment","marker","after","remove","ngMessagesInclude","then","html","$$destroyed","trim","contents"] +} diff --git a/src/main/resources/static/module/angular/angular-mocks.js b/src/main/resources/static/module/angular/angular-mocks.js new file mode 100644 index 0000000..42f19b7 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-mocks.js @@ -0,0 +1,3126 @@ +/** + * @license AngularJS v1.5.8 + * (c) 2010-2016 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular) { + +'use strict'; + +/** + * @ngdoc object + * @name angular.mock + * @description + * + * Namespace from 'angular-mocks.js' which contains testing related code. + * + */ +angular.mock = {}; + +/** + * ! This is a private undocumented service ! + * + * @name $browser + * + * @description + * This service is a mock implementation of {@link ng.$browser}. It provides fake + * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, + * cookies, etc. + * + * The api of this service is the same as that of the real {@link ng.$browser $browser}, except + * that there are several helper methods available which can be used in tests. + */ +angular.mock.$BrowserProvider = function() { + this.$get = function() { + return new angular.mock.$Browser(); + }; +}; + +angular.mock.$Browser = function() { + var self = this; + + this.isMock = true; + self.$$url = "http://server/"; + self.$$lastUrl = self.$$url; // used by url polling fn + self.pollFns = []; + + // TODO(vojta): remove this temporary api + self.$$completeOutstandingRequest = angular.noop; + self.$$incOutstandingRequestCount = angular.noop; + + + // register url polling fn + + self.onUrlChange = function(listener) { + self.pollFns.push( + function() { + if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { + self.$$lastUrl = self.$$url; + self.$$lastState = self.$$state; + listener(self.$$url, self.$$state); + } + } + ); + + return listener; + }; + + self.$$applicationDestroyed = angular.noop; + self.$$checkUrlChange = angular.noop; + + self.deferredFns = []; + self.deferredNextId = 0; + + self.defer = function(fn, delay) { + delay = delay || 0; + self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); + self.deferredFns.sort(function(a, b) { return a.time - b.time;}); + return self.deferredNextId++; + }; + + + /** + * @name $browser#defer.now + * + * @description + * Current milliseconds mock time. + */ + self.defer.now = 0; + + + self.defer.cancel = function(deferId) { + var fnIndex; + + angular.forEach(self.deferredFns, function(fn, index) { + if (fn.id === deferId) fnIndex = index; + }); + + if (angular.isDefined(fnIndex)) { + self.deferredFns.splice(fnIndex, 1); + return true; + } + + return false; + }; + + + /** + * @name $browser#defer.flush + * + * @description + * Flushes all pending requests and executes the defer callbacks. + * + * @param {number=} number of milliseconds to flush. See {@link #defer.now} + */ + self.defer.flush = function(delay) { + var nextTime; + + if (angular.isDefined(delay)) { + // A delay was passed so compute the next time + nextTime = self.defer.now + delay; + } else { + if (self.deferredFns.length) { + // No delay was passed so set the next time so that it clears the deferred queue + nextTime = self.deferredFns[self.deferredFns.length - 1].time; + } else { + // No delay passed, but there are no deferred tasks so flush - indicates an error! + throw new Error('No deferred tasks to be flushed'); + } + } + + while (self.deferredFns.length && self.deferredFns[0].time <= nextTime) { + // Increment the time and call the next deferred function + self.defer.now = self.deferredFns[0].time; + self.deferredFns.shift().fn(); + } + + // Ensure that the current time is correct + self.defer.now = nextTime; + }; + + self.$$baseHref = '/'; + self.baseHref = function() { + return this.$$baseHref; + }; +}; +angular.mock.$Browser.prototype = { + + /** + * @name $browser#poll + * + * @description + * run all fns in pollFns + */ + poll: function poll() { + angular.forEach(this.pollFns, function(pollFn) { + pollFn(); + }); + }, + + url: function(url, replace, state) { + if (angular.isUndefined(state)) { + state = null; + } + if (url) { + this.$$url = url; + // Native pushState serializes & copies the object; simulate it. + this.$$state = angular.copy(state); + return this; + } + + return this.$$url; + }, + + state: function() { + return this.$$state; + }, + + notifyWhenNoOutstandingRequests: function(fn) { + fn(); + } +}; + + +/** + * @ngdoc provider + * @name $exceptionHandlerProvider + * + * @description + * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors + * passed to the `$exceptionHandler`. + */ + +/** + * @ngdoc service + * @name $exceptionHandler + * + * @description + * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed + * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration + * information. + * + * + * ```js + * describe('$exceptionHandlerProvider', function() { + * + * it('should capture log messages and exceptions', function() { + * + * module(function($exceptionHandlerProvider) { + * $exceptionHandlerProvider.mode('log'); + * }); + * + * inject(function($log, $exceptionHandler, $timeout) { + * $timeout(function() { $log.log(1); }); + * $timeout(function() { $log.log(2); throw 'banana peel'; }); + * $timeout(function() { $log.log(3); }); + * expect($exceptionHandler.errors).toEqual([]); + * expect($log.assertEmpty()); + * $timeout.flush(); + * expect($exceptionHandler.errors).toEqual(['banana peel']); + * expect($log.log.logs).toEqual([[1], [2], [3]]); + * }); + * }); + * }); + * ``` + */ + +angular.mock.$ExceptionHandlerProvider = function() { + var handler; + + /** + * @ngdoc method + * @name $exceptionHandlerProvider#mode + * + * @description + * Sets the logging mode. + * + * @param {string} mode Mode of operation, defaults to `rethrow`. + * + * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` + * mode stores an array of errors in `$exceptionHandler.errors`, to allow later assertion of + * them. See {@link ngMock.$log#assertEmpty assertEmpty()} and + * {@link ngMock.$log#reset reset()}. + * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there + * is a bug in the application or test, so this mock will make these tests fail. For any + * implementations that expect exceptions to be thrown, the `rethrow` mode will also maintain + * a log of thrown errors in `$exceptionHandler.errors`. + */ + this.mode = function(mode) { + + switch (mode) { + case 'log': + case 'rethrow': + var errors = []; + handler = function(e) { + if (arguments.length == 1) { + errors.push(e); + } else { + errors.push([].slice.call(arguments, 0)); + } + if (mode === "rethrow") { + throw e; + } + }; + handler.errors = errors; + break; + default: + throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); + } + }; + + this.$get = function() { + return handler; + }; + + this.mode('rethrow'); +}; + + +/** + * @ngdoc service + * @name $log + * + * @description + * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays + * (one array per logging level). These arrays are exposed as `logs` property of each of the + * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. + * + */ +angular.mock.$LogProvider = function() { + var debug = true; + + function concat(array1, array2, index) { + return array1.concat(Array.prototype.slice.call(array2, index)); + } + + this.debugEnabled = function(flag) { + if (angular.isDefined(flag)) { + debug = flag; + return this; + } else { + return debug; + } + }; + + this.$get = function() { + var $log = { + log: function() { $log.log.logs.push(concat([], arguments, 0)); }, + warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, + info: function() { $log.info.logs.push(concat([], arguments, 0)); }, + error: function() { $log.error.logs.push(concat([], arguments, 0)); }, + debug: function() { + if (debug) { + $log.debug.logs.push(concat([], arguments, 0)); + } + } + }; + + /** + * @ngdoc method + * @name $log#reset + * + * @description + * Reset all of the logging arrays to empty. + */ + $log.reset = function() { + /** + * @ngdoc property + * @name $log#log.logs + * + * @description + * Array of messages logged using {@link ng.$log#log `log()`}. + * + * @example + * ```js + * $log.log('Some Log'); + * var first = $log.log.logs.unshift(); + * ``` + */ + $log.log.logs = []; + /** + * @ngdoc property + * @name $log#info.logs + * + * @description + * Array of messages logged using {@link ng.$log#info `info()`}. + * + * @example + * ```js + * $log.info('Some Info'); + * var first = $log.info.logs.unshift(); + * ``` + */ + $log.info.logs = []; + /** + * @ngdoc property + * @name $log#warn.logs + * + * @description + * Array of messages logged using {@link ng.$log#warn `warn()`}. + * + * @example + * ```js + * $log.warn('Some Warning'); + * var first = $log.warn.logs.unshift(); + * ``` + */ + $log.warn.logs = []; + /** + * @ngdoc property + * @name $log#error.logs + * + * @description + * Array of messages logged using {@link ng.$log#error `error()`}. + * + * @example + * ```js + * $log.error('Some Error'); + * var first = $log.error.logs.unshift(); + * ``` + */ + $log.error.logs = []; + /** + * @ngdoc property + * @name $log#debug.logs + * + * @description + * Array of messages logged using {@link ng.$log#debug `debug()`}. + * + * @example + * ```js + * $log.debug('Some Error'); + * var first = $log.debug.logs.unshift(); + * ``` + */ + $log.debug.logs = []; + }; + + /** + * @ngdoc method + * @name $log#assertEmpty + * + * @description + * Assert that all of the logging methods have no logged messages. If any messages are present, + * an exception is thrown. + */ + $log.assertEmpty = function() { + var errors = []; + angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { + angular.forEach($log[logLevel].logs, function(log) { + angular.forEach(log, function(logItem) { + errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + + (logItem.stack || '')); + }); + }); + }); + if (errors.length) { + errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " + + "an expected log message was not checked and removed:"); + errors.push(''); + throw new Error(errors.join('\n---------\n')); + } + }; + + $log.reset(); + return $log; + }; +}; + + +/** + * @ngdoc service + * @name $interval + * + * @description + * Mock implementation of the $interval service. + * + * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to + * move forward by `millis` milliseconds and trigger any functions scheduled to run in that + * time. + * + * @param {function()} fn A function that should be called repeatedly. + * @param {number} delay Number of milliseconds between each function call. + * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat + * indefinitely. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @param {...*=} Pass additional parameters to the executed function. + * @returns {promise} A promise which will be notified on each iteration. + */ +angular.mock.$IntervalProvider = function() { + this.$get = ['$browser', '$rootScope', '$q', '$$q', + function($browser, $rootScope, $q, $$q) { + var repeatFns = [], + nextRepeatId = 0, + now = 0; + + var $interval = function(fn, delay, count, invokeApply) { + var hasParams = arguments.length > 4, + args = hasParams ? Array.prototype.slice.call(arguments, 4) : [], + iteration = 0, + skipApply = (angular.isDefined(invokeApply) && !invokeApply), + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise; + + count = (angular.isDefined(count)) ? count : 0; + promise.then(null, null, (!hasParams) ? fn : function() { + fn.apply(null, args); + }); + + promise.$$intervalId = nextRepeatId; + + function tick() { + deferred.notify(iteration++); + + if (count > 0 && iteration >= count) { + var fnIndex; + deferred.resolve(iteration); + + angular.forEach(repeatFns, function(fn, index) { + if (fn.id === promise.$$intervalId) fnIndex = index; + }); + + if (angular.isDefined(fnIndex)) { + repeatFns.splice(fnIndex, 1); + } + } + + if (skipApply) { + $browser.defer.flush(); + } else { + $rootScope.$apply(); + } + } + + repeatFns.push({ + nextTime:(now + delay), + delay: delay, + fn: tick, + id: nextRepeatId, + deferred: deferred + }); + repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); + + nextRepeatId++; + return promise; + }; + /** + * @ngdoc method + * @name $interval#cancel + * + * @description + * Cancels a task associated with the `promise`. + * + * @param {promise} promise A promise from calling the `$interval` function. + * @returns {boolean} Returns `true` if the task was successfully cancelled. + */ + $interval.cancel = function(promise) { + if (!promise) return false; + var fnIndex; + + angular.forEach(repeatFns, function(fn, index) { + if (fn.id === promise.$$intervalId) fnIndex = index; + }); + + if (angular.isDefined(fnIndex)) { + repeatFns[fnIndex].deferred.reject('canceled'); + repeatFns.splice(fnIndex, 1); + return true; + } + + return false; + }; + + /** + * @ngdoc method + * @name $interval#flush + * @description + * + * Runs interval tasks scheduled to be run in the next `millis` milliseconds. + * + * @param {number=} millis maximum timeout amount to flush up until. + * + * @return {number} The amount of time moved forward. + */ + $interval.flush = function(millis) { + now += millis; + while (repeatFns.length && repeatFns[0].nextTime <= now) { + var task = repeatFns[0]; + task.fn(); + task.nextTime += task.delay; + repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); + } + return millis; + }; + + return $interval; + }]; +}; + + +/* jshint -W101 */ +/* The R_ISO8061_STR regex is never going to fit into the 100 char limit! + * This directive should go inside the anonymous function but a bug in JSHint means that it would + * not be enacted early enough to prevent the warning. + */ +var R_ISO8061_STR = /^(-?\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; + +function jsonStringToDate(string) { + var match; + if (match = string.match(R_ISO8061_STR)) { + var date = new Date(0), + tzHour = 0, + tzMin = 0; + if (match[9]) { + tzHour = toInt(match[9] + match[10]); + tzMin = toInt(match[9] + match[11]); + } + date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); + date.setUTCHours(toInt(match[4] || 0) - tzHour, + toInt(match[5] || 0) - tzMin, + toInt(match[6] || 0), + toInt(match[7] || 0)); + return date; + } + return string; +} + +function toInt(str) { + return parseInt(str, 10); +} + +function padNumberInMock(num, digits, trim) { + var neg = ''; + if (num < 0) { + neg = '-'; + num = -num; + } + num = '' + num; + while (num.length < digits) num = '0' + num; + if (trim) { + num = num.substr(num.length - digits); + } + return neg + num; +} + + +/** + * @ngdoc type + * @name angular.mock.TzDate + * @description + * + * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. + * + * Mock of the Date type which has its timezone specified via constructor arg. + * + * The main purpose is to create Date-like instances with timezone fixed to the specified timezone + * offset, so that we can test code that depends on local timezone settings without dependency on + * the time zone settings of the machine where the code is running. + * + * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) + * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* + * + * @example + * !!!! WARNING !!!!! + * This is not a complete Date object so only methods that were implemented can be called safely. + * To make matters worse, TzDate instances inherit stuff from Date via a prototype. + * + * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is + * incomplete we might be missing some non-standard methods. This can result in errors like: + * "Date.prototype.foo called on incompatible Object". + * + * ```js + * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); + * newYearInBratislava.getTimezoneOffset() => -60; + * newYearInBratislava.getFullYear() => 2010; + * newYearInBratislava.getMonth() => 0; + * newYearInBratislava.getDate() => 1; + * newYearInBratislava.getHours() => 0; + * newYearInBratislava.getMinutes() => 0; + * newYearInBratislava.getSeconds() => 0; + * ``` + * + */ +angular.mock.TzDate = function(offset, timestamp) { + var self = new Date(0); + if (angular.isString(timestamp)) { + var tsStr = timestamp; + + self.origDate = jsonStringToDate(timestamp); + + timestamp = self.origDate.getTime(); + if (isNaN(timestamp)) { + throw { + name: "Illegal Argument", + message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" + }; + } + } else { + self.origDate = new Date(timestamp); + } + + var localOffset = new Date(timestamp).getTimezoneOffset(); + self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; + self.date = new Date(timestamp + self.offsetDiff); + + self.getTime = function() { + return self.date.getTime() - self.offsetDiff; + }; + + self.toLocaleDateString = function() { + return self.date.toLocaleDateString(); + }; + + self.getFullYear = function() { + return self.date.getFullYear(); + }; + + self.getMonth = function() { + return self.date.getMonth(); + }; + + self.getDate = function() { + return self.date.getDate(); + }; + + self.getHours = function() { + return self.date.getHours(); + }; + + self.getMinutes = function() { + return self.date.getMinutes(); + }; + + self.getSeconds = function() { + return self.date.getSeconds(); + }; + + self.getMilliseconds = function() { + return self.date.getMilliseconds(); + }; + + self.getTimezoneOffset = function() { + return offset * 60; + }; + + self.getUTCFullYear = function() { + return self.origDate.getUTCFullYear(); + }; + + self.getUTCMonth = function() { + return self.origDate.getUTCMonth(); + }; + + self.getUTCDate = function() { + return self.origDate.getUTCDate(); + }; + + self.getUTCHours = function() { + return self.origDate.getUTCHours(); + }; + + self.getUTCMinutes = function() { + return self.origDate.getUTCMinutes(); + }; + + self.getUTCSeconds = function() { + return self.origDate.getUTCSeconds(); + }; + + self.getUTCMilliseconds = function() { + return self.origDate.getUTCMilliseconds(); + }; + + self.getDay = function() { + return self.date.getDay(); + }; + + // provide this method only on browsers that already have it + if (self.toISOString) { + self.toISOString = function() { + return padNumberInMock(self.origDate.getUTCFullYear(), 4) + '-' + + padNumberInMock(self.origDate.getUTCMonth() + 1, 2) + '-' + + padNumberInMock(self.origDate.getUTCDate(), 2) + 'T' + + padNumberInMock(self.origDate.getUTCHours(), 2) + ':' + + padNumberInMock(self.origDate.getUTCMinutes(), 2) + ':' + + padNumberInMock(self.origDate.getUTCSeconds(), 2) + '.' + + padNumberInMock(self.origDate.getUTCMilliseconds(), 3) + 'Z'; + }; + } + + //hide all methods not implemented in this mock that the Date prototype exposes + var unimplementedMethods = ['getUTCDay', + 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', + 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', + 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', + 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', + 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; + + angular.forEach(unimplementedMethods, function(methodName) { + self[methodName] = function() { + throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock"); + }; + }); + + return self; +}; + +//make "tzDateInstance instanceof Date" return true +angular.mock.TzDate.prototype = Date.prototype; +/* jshint +W101 */ + + +/** + * @ngdoc service + * @name $animate + * + * @description + * Mock implementation of the {@link ng.$animate `$animate`} service. Exposes two additional methods + * for testing animations. + * + * You need to require the `ngAnimateMock` module in your test suite for instance `beforeEach(module('ngAnimateMock'))` + */ +angular.mock.animate = angular.module('ngAnimateMock', ['ng']) + + .config(['$provide', function($provide) { + + $provide.factory('$$forceReflow', function() { + function reflowFn() { + reflowFn.totalReflows++; + } + reflowFn.totalReflows = 0; + return reflowFn; + }); + + $provide.factory('$$animateAsyncRun', function() { + var queue = []; + var queueFn = function() { + return function(fn) { + queue.push(fn); + }; + }; + queueFn.flush = function() { + if (queue.length === 0) return false; + + for (var i = 0; i < queue.length; i++) { + queue[i](); + } + queue = []; + + return true; + }; + return queueFn; + }); + + $provide.decorator('$$animateJs', ['$delegate', function($delegate) { + var runners = []; + + var animateJsConstructor = function() { + var animator = $delegate.apply($delegate, arguments); + // If no javascript animation is found, animator is undefined + if (animator) { + runners.push(animator); + } + return animator; + }; + + animateJsConstructor.$closeAndFlush = function() { + runners.forEach(function(runner) { + runner.end(); + }); + runners = []; + }; + + return animateJsConstructor; + }]); + + $provide.decorator('$animateCss', ['$delegate', function($delegate) { + var runners = []; + + var animateCssConstructor = function(element, options) { + var animator = $delegate(element, options); + runners.push(animator); + return animator; + }; + + animateCssConstructor.$closeAndFlush = function() { + runners.forEach(function(runner) { + runner.end(); + }); + runners = []; + }; + + return animateCssConstructor; + }]); + + $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$animateCss', '$$animateJs', + '$$forceReflow', '$$animateAsyncRun', '$rootScope', + function($delegate, $timeout, $browser, $$rAF, $animateCss, $$animateJs, + $$forceReflow, $$animateAsyncRun, $rootScope) { + var animate = { + queue: [], + cancel: $delegate.cancel, + on: $delegate.on, + off: $delegate.off, + pin: $delegate.pin, + get reflows() { + return $$forceReflow.totalReflows; + }, + enabled: $delegate.enabled, + /** + * @ngdoc method + * @name $animate#closeAndFlush + * @description + * + * This method will close all pending animations (both {@link ngAnimate#javascript-based-animations Javascript} + * and {@link ngAnimate.$animateCss CSS}) and it will also flush any remaining animation frames and/or callbacks. + */ + closeAndFlush: function() { + // we allow the flush command to swallow the errors + // because depending on whether CSS or JS animations are + // used, there may not be a RAF flush. The primary flush + // at the end of this function must throw an exception + // because it will track if there were pending animations + this.flush(true); + $animateCss.$closeAndFlush(); + $$animateJs.$closeAndFlush(); + this.flush(); + }, + /** + * @ngdoc method + * @name $animate#flush + * @description + * + * This method is used to flush the pending callbacks and animation frames to either start + * an animation or conclude an animation. Note that this will not actually close an + * actively running animation (see {@link ngMock.$animate#closeAndFlush `closeAndFlush()`} for that). + */ + flush: function(hideErrors) { + $rootScope.$digest(); + + var doNextRun, somethingFlushed = false; + do { + doNextRun = false; + + if ($$rAF.queue.length) { + $$rAF.flush(); + doNextRun = somethingFlushed = true; + } + + if ($$animateAsyncRun.flush()) { + doNextRun = somethingFlushed = true; + } + } while (doNextRun); + + if (!somethingFlushed && !hideErrors) { + throw new Error('No pending animations ready to be closed or flushed'); + } + + $rootScope.$digest(); + } + }; + + angular.forEach( + ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { + animate[method] = function() { + animate.queue.push({ + event: method, + element: arguments[0], + options: arguments[arguments.length - 1], + args: arguments + }); + return $delegate[method].apply($delegate, arguments); + }; + }); + + return animate; + }]); + + }]); + + +/** + * @ngdoc function + * @name angular.mock.dump + * @description + * + * *NOTE*: This is not an injectable instance, just a globally available function. + * + * Method for serializing common angular objects (scope, elements, etc..) into strings. + * It is useful for logging objects to the console when debugging. + * + * @param {*} object - any object to turn into string. + * @return {string} a serialized string of the argument + */ +angular.mock.dump = function(object) { + return serialize(object); + + function serialize(object) { + var out; + + if (angular.isElement(object)) { + object = angular.element(object); + out = angular.element('
    '); + angular.forEach(object, function(element) { + out.append(angular.element(element).clone()); + }); + out = out.html(); + } else if (angular.isArray(object)) { + out = []; + angular.forEach(object, function(o) { + out.push(serialize(o)); + }); + out = '[ ' + out.join(', ') + ' ]'; + } else if (angular.isObject(object)) { + if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { + out = serializeScope(object); + } else if (object instanceof Error) { + out = object.stack || ('' + object.name + ': ' + object.message); + } else { + // TODO(i): this prevents methods being logged, + // we should have a better way to serialize objects + out = angular.toJson(object, true); + } + } else { + out = String(object); + } + + return out; + } + + function serializeScope(scope, offset) { + offset = offset || ' '; + var log = [offset + 'Scope(' + scope.$id + '): {']; + for (var key in scope) { + if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { + log.push(' ' + key + ': ' + angular.toJson(scope[key])); + } + } + var child = scope.$$childHead; + while (child) { + log.push(serializeScope(child, offset + ' ')); + child = child.$$nextSibling; + } + log.push('}'); + return log.join('\n' + offset); + } +}; + +/** + * @ngdoc service + * @name $httpBackend + * @description + * Fake HTTP backend implementation suitable for unit testing applications that use the + * {@link ng.$http $http service}. + * + *
    + * **Note**: For fake HTTP backend implementation suitable for end-to-end testing or backend-less + * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. + *
    + * + * During unit testing, we want our unit tests to run quickly and have no external dependencies so + * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or + * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is + * to verify whether a certain request has been sent or not, or alternatively just let the + * application make requests, respond with pre-trained responses and assert that the end result is + * what we expect it to be. + * + * This mock implementation can be used to respond with static or dynamic responses via the + * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). + * + * When an Angular application needs some data from a server, it calls the $http service, which + * sends the request to a real server using $httpBackend service. With dependency injection, it is + * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify + * the requests and respond with some testing data without sending a request to a real server. + * + * There are two ways to specify what test data should be returned as http responses by the mock + * backend when the code under test makes http requests: + * + * - `$httpBackend.expect` - specifies a request expectation + * - `$httpBackend.when` - specifies a backend definition + * + * + * ## Request Expectations vs Backend Definitions + * + * Request expectations provide a way to make assertions about requests made by the application and + * to define responses for those requests. The test will fail if the expected requests are not made + * or they are made in the wrong order. + * + * Backend definitions allow you to define a fake backend for your application which doesn't assert + * if a particular request was made or not, it just returns a trained response if a request is made. + * The test will pass whether or not the request gets made during testing. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Request expectationsBackend definitions
    Syntax.expect(...).respond(...).when(...).respond(...)
    Typical usagestrict unit testsloose (black-box) unit testing
    Fulfills multiple requestsNOYES
    Order of requests mattersYESNO
    Request requiredYESNO
    Response requiredoptional (see below)YES
    + * + * In cases where both backend definitions and request expectations are specified during unit + * testing, the request expectations are evaluated first. + * + * If a request expectation has no response specified, the algorithm will search your backend + * definitions for an appropriate response. + * + * If a request didn't match any expectation or if the expectation doesn't have the response + * defined, the backend definitions are evaluated in sequential order to see if any of them match + * the request. The response from the first matched definition is returned. + * + * + * ## Flushing HTTP requests + * + * The $httpBackend used in production always responds to requests asynchronously. If we preserved + * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, + * to follow and to maintain. But neither can the testing mock respond synchronously; that would + * change the execution of the code under test. For this reason, the mock $httpBackend has a + * `flush()` method, which allows the test to explicitly flush pending requests. This preserves + * the async api of the backend, while allowing the test to execute synchronously. + * + * + * ## Unit testing with mock $httpBackend + * The following code shows how to setup and use the mock backend when unit testing a controller. + * First we create the controller under test: + * + ```js + // The module code + angular + .module('MyApp', []) + .controller('MyController', MyController); + + // The controller code + function MyController($scope, $http) { + var authToken; + + $http.get('/auth.py').then(function(response) { + authToken = response.headers('A-Token'); + $scope.user = response.data; + }); + + $scope.saveMessage = function(message) { + var headers = { 'Authorization': authToken }; + $scope.status = 'Saving...'; + + $http.post('/add-msg.py', message, { headers: headers } ).then(function(response) { + $scope.status = ''; + }).catch(function() { + $scope.status = 'Failed...'; + }); + }; + } + ``` + * + * Now we setup the mock backend and create the test specs: + * + ```js + // testing controller + describe('MyController', function() { + var $httpBackend, $rootScope, createController, authRequestHandler; + + // Set up the module + beforeEach(module('MyApp')); + + beforeEach(inject(function($injector) { + // Set up the mock http service responses + $httpBackend = $injector.get('$httpBackend'); + // backend definition common for all tests + authRequestHandler = $httpBackend.when('GET', '/auth.py') + .respond({userId: 'userX'}, {'A-Token': 'xxx'}); + + // Get hold of a scope (i.e. the root scope) + $rootScope = $injector.get('$rootScope'); + // The $controller service is used to create instances of controllers + var $controller = $injector.get('$controller'); + + createController = function() { + return $controller('MyController', {'$scope' : $rootScope }); + }; + })); + + + afterEach(function() { + $httpBackend.verifyNoOutstandingExpectation(); + $httpBackend.verifyNoOutstandingRequest(); + }); + + + it('should fetch authentication token', function() { + $httpBackend.expectGET('/auth.py'); + var controller = createController(); + $httpBackend.flush(); + }); + + + it('should fail authentication', function() { + + // Notice how you can change the response even after it was set + authRequestHandler.respond(401, ''); + + $httpBackend.expectGET('/auth.py'); + var controller = createController(); + $httpBackend.flush(); + expect($rootScope.status).toBe('Failed...'); + }); + + + it('should send msg to server', function() { + var controller = createController(); + $httpBackend.flush(); + + // now you don’t care about the authentication, but + // the controller will still send the request and + // $httpBackend will respond without you having to + // specify the expectation and response for this request + + $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); + $rootScope.saveMessage('message content'); + expect($rootScope.status).toBe('Saving...'); + $httpBackend.flush(); + expect($rootScope.status).toBe(''); + }); + + + it('should send auth header', function() { + var controller = createController(); + $httpBackend.flush(); + + $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { + // check if the header was sent, if it wasn't the expectation won't + // match the request and the test will fail + return headers['Authorization'] == 'xxx'; + }).respond(201, ''); + + $rootScope.saveMessage('whatever'); + $httpBackend.flush(); + }); + }); + ``` + * + * ## Dynamic responses + * + * You define a response to a request by chaining a call to `respond()` onto a definition or expectation. + * If you provide a **callback** as the first parameter to `respond(callback)` then you can dynamically generate + * a response based on the properties of the request. + * + * The `callback` function should be of the form `function(method, url, data, headers, params)`. + * + * ### Query parameters + * + * By default, query parameters on request URLs are parsed into the `params` object. So a request URL + * of `/list?q=searchstr&orderby=-name` would set `params` to be `{q: 'searchstr', orderby: '-name'}`. + * + * ### Regex parameter matching + * + * If an expectation or definition uses a **regex** to match the URL, you can provide an array of **keys** via a + * `params` argument. The index of each **key** in the array will match the index of a **group** in the + * **regex**. + * + * The `params` object in the **callback** will now have properties with these keys, which hold the value of the + * corresponding **group** in the **regex**. + * + * This also applies to the `when` and `expect` shortcut methods. + * + * + * ```js + * $httpBackend.expect('GET', /\/user\/(.+)/, undefined, undefined, ['id']) + * .respond(function(method, url, data, headers, params) { + * // for requested url of '/user/1234' params is {id: '1234'} + * }); + * + * $httpBackend.whenPATCH(/\/user\/(.+)\/article\/(.+)/, undefined, undefined, ['user', 'article']) + * .respond(function(method, url, data, headers, params) { + * // for url of '/user/1234/article/567' params is {user: '1234', article: '567'} + * }); + * ``` + * + * ## Matching route requests + * + * For extra convenience, `whenRoute` and `expectRoute` shortcuts are available. These methods offer colon + * delimited matching of the url path, ignoring the query string. This allows declarations + * similar to how application routes are configured with `$routeProvider`. Because these methods convert + * the definition url to regex, declaration order is important. Combined with query parameter parsing, + * the following is possible: + * + ```js + $httpBackend.whenRoute('GET', '/users/:id') + .respond(function(method, url, data, headers, params) { + return [200, MockUserList[Number(params.id)]]; + }); + + $httpBackend.whenRoute('GET', '/users') + .respond(function(method, url, data, headers, params) { + var userList = angular.copy(MockUserList), + defaultSort = 'lastName', + count, pages, isPrevious, isNext; + + // paged api response '/v1/users?page=2' + params.page = Number(params.page) || 1; + + // query for last names '/v1/users?q=Archer' + if (params.q) { + userList = $filter('filter')({lastName: params.q}); + } + + pages = Math.ceil(userList.length / pagingLength); + isPrevious = params.page > 1; + isNext = params.page < pages; + + return [200, { + count: userList.length, + previous: isPrevious, + next: isNext, + // sort field -> '/v1/users?sortBy=firstName' + results: $filter('orderBy')(userList, params.sortBy || defaultSort) + .splice((params.page - 1) * pagingLength, pagingLength) + }]; + }); + ``` + */ +angular.mock.$HttpBackendProvider = function() { + this.$get = ['$rootScope', '$timeout', createHttpBackendMock]; +}; + +/** + * General factory function for $httpBackend mock. + * Returns instance for unit testing (when no arguments specified): + * - passing through is disabled + * - auto flushing is disabled + * + * Returns instance for e2e testing (when `$delegate` and `$browser` specified): + * - passing through (delegating request to real backend) is enabled + * - auto flushing is enabled + * + * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) + * @param {Object=} $browser Auto-flushing enabled if specified + * @return {Object} Instance of $httpBackend mock + */ +function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { + var definitions = [], + expectations = [], + responses = [], + responsesPush = angular.bind(responses, responses.push), + copy = angular.copy; + + function createResponse(status, data, headers, statusText) { + if (angular.isFunction(status)) return status; + + return function() { + return angular.isNumber(status) + ? [status, data, headers, statusText] + : [200, status, data, headers]; + }; + } + + // TODO(vojta): change params to: method, url, data, headers, callback + function $httpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { + + var xhr = new MockXhr(), + expectation = expectations[0], + wasExpected = false; + + xhr.$$events = eventHandlers; + xhr.upload.$$events = uploadEventHandlers; + + function prettyPrint(data) { + return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) + ? data + : angular.toJson(data); + } + + function wrapResponse(wrapped) { + if (!$browser && timeout) { + timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout); + } + + return handleResponse; + + function handleResponse() { + var response = wrapped.response(method, url, data, headers, wrapped.params(url)); + xhr.$$respHeaders = response[2]; + callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), + copy(response[3] || '')); + } + + function handleTimeout() { + for (var i = 0, ii = responses.length; i < ii; i++) { + if (responses[i] === handleResponse) { + responses.splice(i, 1); + callback(-1, undefined, ''); + break; + } + } + } + } + + if (expectation && expectation.match(method, url)) { + if (!expectation.matchData(data)) { + throw new Error('Expected ' + expectation + ' with different data\n' + + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); + } + + if (!expectation.matchHeaders(headers)) { + throw new Error('Expected ' + expectation + ' with different headers\n' + + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + + prettyPrint(headers)); + } + + expectations.shift(); + + if (expectation.response) { + responses.push(wrapResponse(expectation)); + return; + } + wasExpected = true; + } + + var i = -1, definition; + while ((definition = definitions[++i])) { + if (definition.match(method, url, data, headers || {})) { + if (definition.response) { + // if $browser specified, we do auto flush all requests + ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); + } else if (definition.passThrough) { + $delegate(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers); + } else throw new Error('No response defined !'); + return; + } + } + throw wasExpected ? + new Error('No response defined !') : + new Error('Unexpected request: ' + method + ' ' + url + '\n' + + (expectation ? 'Expected ' + expectation : 'No more request expected')); + } + + /** + * @ngdoc method + * @name $httpBackend#when + * @description + * Creates a new backend definition. + * + * @param {string} method HTTP method. + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. + * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header + * object and returns true if the headers match the current definition. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + * + * - respond – + * ```js + * {function([status,] data[, headers, statusText]) + * | function(function(method, url, data, headers, params)} + * ``` + * – The respond method takes a set of static data to be returned or a function that can + * return an array containing response status (number), response data (Array|Object|string), + * response headers (Object), and the text for the status (string). The respond method returns + * the `requestHandler` object for possible overrides. + */ + $httpBackend.when = function(method, url, data, headers, keys) { + var definition = new MockHttpExpectation(method, url, data, headers, keys), + chain = { + respond: function(status, data, headers, statusText) { + definition.passThrough = undefined; + definition.response = createResponse(status, data, headers, statusText); + return chain; + } + }; + + if ($browser) { + chain.passThrough = function() { + definition.response = undefined; + definition.passThrough = true; + return chain; + }; + } + + definitions.push(definition); + return chain; + }; + + /** + * @ngdoc method + * @name $httpBackend#whenGET + * @description + * Creates a new backend definition for GET requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#whenHEAD + * @description + * Creates a new backend definition for HEAD requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#whenDELETE + * @description + * Creates a new backend definition for DELETE requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#whenPOST + * @description + * Creates a new backend definition for POST requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#whenPUT + * @description + * Creates a new backend definition for PUT requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives + * data string and returns true if the data is as expected. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#whenJSONP + * @description + * Creates a new backend definition for JSONP requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + createShortMethods('when'); + + /** + * @ngdoc method + * @name $httpBackend#whenRoute + * @description + * Creates a new backend definition that compares only with the requested route. + * + * @param {string} method HTTP method. + * @param {string} url HTTP url string that supports colon param matching. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. See #when for more info. + */ + $httpBackend.whenRoute = function(method, url) { + var pathObj = parseRoute(url); + return $httpBackend.when(method, pathObj.regexp, undefined, undefined, pathObj.keys); + }; + + function parseRoute(url) { + var ret = { + regexp: url + }, + keys = ret.keys = []; + + if (!url || !angular.isString(url)) return ret; + + url = url + .replace(/([().])/g, '\\$1') + .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) { + var optional = option === '?' ? option : null; + var star = option === '*' ? option : null; + keys.push({ name: key, optional: !!optional }); + slash = slash || ''; + return '' + + (optional ? '' : slash) + + '(?:' + + (optional ? slash : '') + + (star && '(.+?)' || '([^/]+)') + + (optional || '') + + ')' + + (optional || ''); + }) + .replace(/([\/$\*])/g, '\\$1'); + + ret.regexp = new RegExp('^' + url, 'i'); + return ret; + } + + /** + * @ngdoc method + * @name $httpBackend#expect + * @description + * Creates a new request expectation. + * + * @param {string} method HTTP method. + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header + * object and returns true if the headers match the current expectation. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + * + * - respond – + * ``` + * { function([status,] data[, headers, statusText]) + * | function(function(method, url, data, headers, params)} + * ``` + * – The respond method takes a set of static data to be returned or a function that can + * return an array containing response status (number), response data (Array|Object|string), + * response headers (Object), and the text for the status (string). The respond method returns + * the `requestHandler` object for possible overrides. + */ + $httpBackend.expect = function(method, url, data, headers, keys) { + var expectation = new MockHttpExpectation(method, url, data, headers, keys), + chain = { + respond: function(status, data, headers, statusText) { + expectation.response = createResponse(status, data, headers, statusText); + return chain; + } + }; + + expectations.push(expectation); + return chain; + }; + + /** + * @ngdoc method + * @name $httpBackend#expectGET + * @description + * Creates a new request expectation for GET requests. For more info see `expect()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {Object=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. See #expect for more info. + */ + + /** + * @ngdoc method + * @name $httpBackend#expectHEAD + * @description + * Creates a new request expectation for HEAD requests. For more info see `expect()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {Object=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#expectDELETE + * @description + * Creates a new request expectation for DELETE requests. For more info see `expect()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {Object=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#expectPOST + * @description + * Creates a new request expectation for POST requests. For more info see `expect()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {Object=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#expectPUT + * @description + * Creates a new request expectation for PUT requests. For more info see `expect()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {Object=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#expectPATCH + * @description + * Creates a new request expectation for PATCH requests. For more info see `expect()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that + * receives data string and returns true if the data is as expected, or Object if request body + * is in JSON format. + * @param {Object=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + + /** + * @ngdoc method + * @name $httpBackend#expectJSONP + * @description + * Creates a new request expectation for JSONP requests. For more info see `expect()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives an url + * and returns true if the url matches the current definition. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. + */ + createShortMethods('expect'); + + /** + * @ngdoc method + * @name $httpBackend#expectRoute + * @description + * Creates a new request expectation that compares only with the requested route. + * + * @param {string} method HTTP method. + * @param {string} url HTTP url string that supports colon param matching. + * @returns {requestHandler} Returns an object with `respond` method that controls how a matched + * request is handled. You can save this object for later use and invoke `respond` again in + * order to change how a matched request is handled. See #expect for more info. + */ + $httpBackend.expectRoute = function(method, url) { + var pathObj = parseRoute(url); + return $httpBackend.expect(method, pathObj.regexp, undefined, undefined, pathObj.keys); + }; + + + /** + * @ngdoc method + * @name $httpBackend#flush + * @description + * Flushes all pending requests using the trained responses. + * + * @param {number=} count Number of responses to flush (in the order they arrived). If undefined, + * all pending requests will be flushed. If there are no pending requests when the flush method + * is called an exception is thrown (as this typically a sign of programming error). + */ + $httpBackend.flush = function(count, digest) { + if (digest !== false) $rootScope.$digest(); + if (!responses.length) throw new Error('No pending request to flush !'); + + if (angular.isDefined(count) && count !== null) { + while (count--) { + if (!responses.length) throw new Error('No more pending request to flush !'); + responses.shift()(); + } + } else { + while (responses.length) { + responses.shift()(); + } + } + $httpBackend.verifyNoOutstandingExpectation(digest); + }; + + + /** + * @ngdoc method + * @name $httpBackend#verifyNoOutstandingExpectation + * @description + * Verifies that all of the requests defined via the `expect` api were made. If any of the + * requests were not made, verifyNoOutstandingExpectation throws an exception. + * + * Typically, you would call this method following each test case that asserts requests using an + * "afterEach" clause. + * + * ```js + * afterEach($httpBackend.verifyNoOutstandingExpectation); + * ``` + */ + $httpBackend.verifyNoOutstandingExpectation = function(digest) { + if (digest !== false) $rootScope.$digest(); + if (expectations.length) { + throw new Error('Unsatisfied requests: ' + expectations.join(', ')); + } + }; + + + /** + * @ngdoc method + * @name $httpBackend#verifyNoOutstandingRequest + * @description + * Verifies that there are no outstanding requests that need to be flushed. + * + * Typically, you would call this method following each test case that asserts requests using an + * "afterEach" clause. + * + * ```js + * afterEach($httpBackend.verifyNoOutstandingRequest); + * ``` + */ + $httpBackend.verifyNoOutstandingRequest = function() { + if (responses.length) { + throw new Error('Unflushed requests: ' + responses.length); + } + }; + + + /** + * @ngdoc method + * @name $httpBackend#resetExpectations + * @description + * Resets all request expectations, but preserves all backend definitions. Typically, you would + * call resetExpectations during a multiple-phase test when you want to reuse the same instance of + * $httpBackend mock. + */ + $httpBackend.resetExpectations = function() { + expectations.length = 0; + responses.length = 0; + }; + + return $httpBackend; + + + function createShortMethods(prefix) { + angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) { + $httpBackend[prefix + method] = function(url, headers, keys) { + return $httpBackend[prefix](method, url, undefined, headers, keys); + }; + }); + + angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { + $httpBackend[prefix + method] = function(url, data, headers, keys) { + return $httpBackend[prefix](method, url, data, headers, keys); + }; + }); + } +} + +function MockHttpExpectation(method, url, data, headers, keys) { + + function getUrlParams(u) { + var params = u.slice(u.indexOf('?') + 1).split('&'); + return params.sort(); + } + + function compareUrl(u) { + return (url.slice(0, url.indexOf('?')) == u.slice(0, u.indexOf('?')) && getUrlParams(url).join() == getUrlParams(u).join()); + } + + this.data = data; + this.headers = headers; + + this.match = function(m, u, d, h) { + if (method != m) return false; + if (!this.matchUrl(u)) return false; + if (angular.isDefined(d) && !this.matchData(d)) return false; + if (angular.isDefined(h) && !this.matchHeaders(h)) return false; + return true; + }; + + this.matchUrl = function(u) { + if (!url) return true; + if (angular.isFunction(url.test)) return url.test(u); + if (angular.isFunction(url)) return url(u); + return (url == u || compareUrl(u)); + }; + + this.matchHeaders = function(h) { + if (angular.isUndefined(headers)) return true; + if (angular.isFunction(headers)) return headers(h); + return angular.equals(headers, h); + }; + + this.matchData = function(d) { + if (angular.isUndefined(data)) return true; + if (data && angular.isFunction(data.test)) return data.test(d); + if (data && angular.isFunction(data)) return data(d); + if (data && !angular.isString(data)) { + return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d)); + } + return data == d; + }; + + this.toString = function() { + return method + ' ' + url; + }; + + this.params = function(u) { + return angular.extend(parseQuery(), pathParams()); + + function pathParams() { + var keyObj = {}; + if (!url || !angular.isFunction(url.test) || !keys || keys.length === 0) return keyObj; + + var m = url.exec(u); + if (!m) return keyObj; + for (var i = 1, len = m.length; i < len; ++i) { + var key = keys[i - 1]; + var val = m[i]; + if (key && val) { + keyObj[key.name || key] = val; + } + } + + return keyObj; + } + + function parseQuery() { + var obj = {}, key_value, key, + queryStr = u.indexOf('?') > -1 + ? u.substring(u.indexOf('?') + 1) + : ""; + + angular.forEach(queryStr.split('&'), function(keyValue) { + if (keyValue) { + key_value = keyValue.replace(/\+/g,'%20').split('='); + key = tryDecodeURIComponent(key_value[0]); + if (angular.isDefined(key)) { + var val = angular.isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; + if (!hasOwnProperty.call(obj, key)) { + obj[key] = val; + } else if (angular.isArray(obj[key])) { + obj[key].push(val); + } else { + obj[key] = [obj[key],val]; + } + } + } + }); + return obj; + } + function tryDecodeURIComponent(value) { + try { + return decodeURIComponent(value); + } catch (e) { + // Ignore any invalid uri component + } + } + }; +} + +function createMockXhr() { + return new MockXhr(); +} + +function MockXhr() { + + // hack for testing $http, $httpBackend + MockXhr.$$lastInstance = this; + + this.open = function(method, url, async) { + this.$$method = method; + this.$$url = url; + this.$$async = async; + this.$$reqHeaders = {}; + this.$$respHeaders = {}; + }; + + this.send = function(data) { + this.$$data = data; + }; + + this.setRequestHeader = function(key, value) { + this.$$reqHeaders[key] = value; + }; + + this.getResponseHeader = function(name) { + // the lookup must be case insensitive, + // that's why we try two quick lookups first and full scan last + var header = this.$$respHeaders[name]; + if (header) return header; + + name = angular.lowercase(name); + header = this.$$respHeaders[name]; + if (header) return header; + + header = undefined; + angular.forEach(this.$$respHeaders, function(headerVal, headerName) { + if (!header && angular.lowercase(headerName) == name) header = headerVal; + }); + return header; + }; + + this.getAllResponseHeaders = function() { + var lines = []; + + angular.forEach(this.$$respHeaders, function(value, key) { + lines.push(key + ': ' + value); + }); + return lines.join('\n'); + }; + + this.abort = angular.noop; + + // This section simulates the events on a real XHR object (and the upload object) + // When we are testing $httpBackend (inside the angular project) we make partial use of this + // but store the events directly ourselves on `$$events`, instead of going through the `addEventListener` + this.$$events = {}; + this.addEventListener = function(name, listener) { + if (angular.isUndefined(this.$$events[name])) this.$$events[name] = []; + this.$$events[name].push(listener); + }; + + this.upload = { + $$events: {}, + addEventListener: this.addEventListener + }; +} + + +/** + * @ngdoc service + * @name $timeout + * @description + * + * This service is just a simple decorator for {@link ng.$timeout $timeout} service + * that adds a "flush" and "verifyNoPendingTasks" methods. + */ + +angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) { + + /** + * @ngdoc method + * @name $timeout#flush + * @description + * + * Flushes the queue of pending tasks. + * + * @param {number=} delay maximum timeout amount to flush up until + */ + $delegate.flush = function(delay) { + $browser.defer.flush(delay); + }; + + /** + * @ngdoc method + * @name $timeout#verifyNoPendingTasks + * @description + * + * Verifies that there are no pending tasks that need to be flushed. + */ + $delegate.verifyNoPendingTasks = function() { + if ($browser.deferredFns.length) { + throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + + formatPendingTasksAsString($browser.deferredFns)); + } + }; + + function formatPendingTasksAsString(tasks) { + var result = []; + angular.forEach(tasks, function(task) { + result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); + }); + + return result.join(', '); + } + + return $delegate; +}]; + +angular.mock.$RAFDecorator = ['$delegate', function($delegate) { + var rafFn = function(fn) { + var index = rafFn.queue.length; + rafFn.queue.push(fn); + return function() { + rafFn.queue.splice(index, 1); + }; + }; + + rafFn.queue = []; + rafFn.supported = $delegate.supported; + + rafFn.flush = function() { + if (rafFn.queue.length === 0) { + throw new Error('No rAF callbacks present'); + } + + var length = rafFn.queue.length; + for (var i = 0; i < length; i++) { + rafFn.queue[i](); + } + + rafFn.queue = rafFn.queue.slice(i); + }; + + return rafFn; +}]; + +/** + * + */ +var originalRootElement; +angular.mock.$RootElementProvider = function() { + this.$get = ['$injector', function($injector) { + originalRootElement = angular.element('
    ').data('$injector', $injector); + return originalRootElement; + }]; +}; + +/** + * @ngdoc service + * @name $controller + * @description + * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing + * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}. + * + * + * ## Example + * + * ```js + * + * // Directive definition ... + * + * myMod.directive('myDirective', { + * controller: 'MyDirectiveController', + * bindToController: { + * name: '@' + * } + * }); + * + * + * // Controller definition ... + * + * myMod.controller('MyDirectiveController', ['$log', function($log) { + * $log.info(this.name); + * }]); + * + * + * // In a test ... + * + * describe('myDirectiveController', function() { + * it('should write the bound name to the log', inject(function($controller, $log) { + * var ctrl = $controller('MyDirectiveController', { /* no locals */ }, { name: 'Clark Kent' }); + * expect(ctrl.name).toEqual('Clark Kent'); + * expect($log.info.logs).toEqual(['Clark Kent']); + * })); + * }); + * + * ``` + * + * @param {Function|string} constructor If called with a function then it's considered to be the + * controller constructor function. Otherwise it's considered to be a string which is used + * to retrieve the controller constructor using the following steps: + * + * * check if a controller with given name is registered via `$controllerProvider` + * * check if evaluating the string on the current scope returns a constructor + * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global + * `window` object (not recommended) + * + * The string can use the `controller as property` syntax, where the controller instance is published + * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this + * to work correctly. + * + * @param {Object} locals Injection locals for Controller. + * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used + * to simulate the `bindToController` feature and simplify certain kinds of tests. + * @return {Object} Instance of given controller. + */ +angular.mock.$ControllerDecorator = ['$delegate', function($delegate) { + return function(expression, locals, later, ident) { + if (later && typeof later === 'object') { + var instantiate = $delegate(expression, locals, true, ident); + angular.extend(instantiate.instance, later); + + var instance = instantiate(); + if (instance !== instantiate.instance) { + angular.extend(instance, later); + } + + return instance; + } + return $delegate(expression, locals, later, ident); + }; +}]; + +/** + * @ngdoc service + * @name $componentController + * @description + * A service that can be used to create instances of component controllers. + *
    + * Be aware that the controller will be instantiated and attached to the scope as specified in + * the component definition object. If you do not provide a `$scope` object in the `locals` param + * then the helper will create a new isolated scope as a child of `$rootScope`. + *
    + * @param {string} componentName the name of the component whose controller we want to instantiate + * @param {Object} locals Injection locals for Controller. + * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used + * to simulate the `bindToController` feature and simplify certain kinds of tests. + * @param {string=} ident Override the property name to use when attaching the controller to the scope. + * @return {Object} Instance of requested controller. + */ +angular.mock.$ComponentControllerProvider = ['$compileProvider', function($compileProvider) { + this.$get = ['$controller','$injector', '$rootScope', function($controller, $injector, $rootScope) { + return function $componentController(componentName, locals, bindings, ident) { + // get all directives associated to the component name + var directives = $injector.get(componentName + 'Directive'); + // look for those directives that are components + var candidateDirectives = directives.filter(function(directiveInfo) { + // components have controller, controllerAs and restrict:'E' + return directiveInfo.controller && directiveInfo.controllerAs && directiveInfo.restrict === 'E'; + }); + // check if valid directives found + if (candidateDirectives.length === 0) { + throw new Error('No component found'); + } + if (candidateDirectives.length > 1) { + throw new Error('Too many components found'); + } + // get the info of the component + var directiveInfo = candidateDirectives[0]; + // create a scope if needed + locals = locals || {}; + locals.$scope = locals.$scope || $rootScope.$new(true); + return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs); + }; + }]; +}]; + + +/** + * @ngdoc module + * @name ngMock + * @packageName angular-mocks + * @description + * + * # ngMock + * + * The `ngMock` module provides support to inject and mock Angular services into unit tests. + * In addition, ngMock also extends various core ng services such that they can be + * inspected and controlled in a synchronous manner within test code. + * + * + *
    + * + * @installation + * + * First, download the file: + * * [Google CDN](https://developers.google.com/speed/libraries/devguide#angularjs) e.g. + * `"//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mocks.js"` + * * [NPM](https://www.npmjs.com/) e.g. `npm install angular-mocks@X.Y.Z` + * * [Bower](http://bower.io) e.g. `bower install angular-mocks#X.Y.Z` + * * [code.angularjs.org](https://code.angularjs.org/) (discouraged for production use) e.g. + * `"//code.angularjs.org/X.Y.Z/angular-mocks.js"` + * + * where X.Y.Z is the AngularJS version you are running. + * + * Then, configure your test runner to load `angular-mocks.js` after `angular.js`. + * This example uses Karma: + * + * ``` + * config.set({ + * files: [ + * 'build/angular.js', // and other module files you need + * 'build/angular-mocks.js', + * '', + * '' + * ] + * }); + * ``` + * + * Including the `angular-mocks.js` file automatically adds the `ngMock` module, so your tests + * are ready to go! + */ +angular.module('ngMock', ['ng']).provider({ + $browser: angular.mock.$BrowserProvider, + $exceptionHandler: angular.mock.$ExceptionHandlerProvider, + $log: angular.mock.$LogProvider, + $interval: angular.mock.$IntervalProvider, + $httpBackend: angular.mock.$HttpBackendProvider, + $rootElement: angular.mock.$RootElementProvider, + $componentController: angular.mock.$ComponentControllerProvider +}).config(['$provide', function($provide) { + $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); + $provide.decorator('$$rAF', angular.mock.$RAFDecorator); + $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); + $provide.decorator('$controller', angular.mock.$ControllerDecorator); +}]); + +/** + * @ngdoc module + * @name ngMockE2E + * @module ngMockE2E + * @packageName angular-mocks + * @description + * + * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. + * Currently there is only one mock present in this module - + * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. + */ +angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { + $provide.value('$httpBackend', angular.injector(['ng']).get('$httpBackend')); + $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); +}]); + +/** + * @ngdoc service + * @name $httpBackend + * @module ngMockE2E + * @description + * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of + * applications that use the {@link ng.$http $http service}. + * + *
    + * **Note**: For fake http backend implementation suitable for unit testing please see + * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. + *
    + * + * This implementation can be used to respond with static or dynamic responses via the `when` api + * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the + * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch + * templates from a webserver). + * + * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application + * is being developed with the real backend api replaced with a mock, it is often desirable for + * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch + * templates or static files from the webserver). To configure the backend with this behavior + * use the `passThrough` request handler of `when` instead of `respond`. + * + * Additionally, we don't want to manually have to flush mocked out requests like we do during unit + * testing. For this reason the e2e $httpBackend flushes mocked out requests + * automatically, closely simulating the behavior of the XMLHttpRequest object. + * + * To setup the application to run with this http backend, you have to create a module that depends + * on the `ngMockE2E` and your application modules and defines the fake backend: + * + * ```js + * var myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); + * myAppDev.run(function($httpBackend) { + * var phones = [{name: 'phone1'}, {name: 'phone2'}]; + * + * // returns the current list of phones + * $httpBackend.whenGET('/phones').respond(phones); + * + * // adds a new phone to the phones array + * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { + * var phone = angular.fromJson(data); + * phones.push(phone); + * return [200, phone, {}]; + * }); + * $httpBackend.whenGET(/^\/templates\//).passThrough(); // Requests for templare are handled by the real server + * //... + * }); + * ``` + * + * Afterwards, bootstrap your app with this new module. + * + * ## Example + * + * + * var myApp = angular.module('myApp', []); + * + * myApp.controller('main', function($http) { + * var ctrl = this; + * + * ctrl.phones = []; + * ctrl.newPhone = { + * name: '' + * }; + * + * ctrl.getPhones = function() { + * $http.get('/phones').then(function(response) { + * ctrl.phones = response.data; + * }); + * }; + * + * ctrl.addPhone = function(phone) { + * $http.post('/phones', phone).then(function() { + * ctrl.newPhone = {name: ''}; + * return ctrl.getPhones(); + * }); + * }; + * + * ctrl.getPhones(); + * }); + * + * + * var myAppDev = angular.module('myAppE2E', ['myApp', 'ngMockE2E']); + * + * myAppDev.run(function($httpBackend) { + * var phones = [{name: 'phone1'}, {name: 'phone2'}]; + * + * // returns the current list of phones + * $httpBackend.whenGET('/phones').respond(phones); + * + * // adds a new phone to the phones array + * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { + * var phone = angular.fromJson(data); + * phones.push(phone); + * return [200, phone, {}]; + * }); + * }); + * + * + *
    + *
    + * + * + *
    + *

    Phones

    + *
      + *
    • {{phone.name}}
    • + *
    + *
    + *
    + *
    + * + * + */ + +/** + * @ngdoc method + * @name $httpBackend#when + * @module ngMockE2E + * @description + * Creates a new backend definition. + * + * @param {string} method HTTP method. + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header + * object and returns true if the headers match the current definition. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + * + * - respond – + * ``` + * { function([status,] data[, headers, statusText]) + * | function(function(method, url, data, headers, params)} + * ``` + * – The respond method takes a set of static data to be returned or a function that can return + * an array containing response status (number), response data (Array|Object|string), response + * headers (Object), and the text for the status (string). + * - passThrough – `{function()}` – Any request matching a backend definition with + * `passThrough` handler will be passed through to the real backend (an XHR request will be made + * to the server.) + * - Both methods return the `requestHandler` object for possible overrides. + */ + +/** + * @ngdoc method + * @name $httpBackend#whenGET + * @module ngMockE2E + * @description + * Creates a new backend definition for GET requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ + +/** + * @ngdoc method + * @name $httpBackend#whenHEAD + * @module ngMockE2E + * @description + * Creates a new backend definition for HEAD requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ + +/** + * @ngdoc method + * @name $httpBackend#whenDELETE + * @module ngMockE2E + * @description + * Creates a new backend definition for DELETE requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ + +/** + * @ngdoc method + * @name $httpBackend#whenPOST + * @module ngMockE2E + * @description + * Creates a new backend definition for POST requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ + +/** + * @ngdoc method + * @name $httpBackend#whenPUT + * @module ngMockE2E + * @description + * Creates a new backend definition for PUT requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ + +/** + * @ngdoc method + * @name $httpBackend#whenPATCH + * @module ngMockE2E + * @description + * Creates a new backend definition for PATCH requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(string|RegExp)=} data HTTP request body. + * @param {(Object|function(Object))=} headers HTTP headers. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ + +/** + * @ngdoc method + * @name $httpBackend#whenJSONP + * @module ngMockE2E + * @description + * Creates a new backend definition for JSONP requests. For more info see `when()`. + * + * @param {string|RegExp|function(string)} url HTTP url or function that receives a url + * and returns true if the url matches the current definition. + * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on + * {@link ngMock.$httpBackend $httpBackend mock}. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ +/** + * @ngdoc method + * @name $httpBackend#whenRoute + * @module ngMockE2E + * @description + * Creates a new backend definition that compares only with the requested route. + * + * @param {string} method HTTP method. + * @param {string} url HTTP url string that supports colon param matching. + * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that + * control how a matched request is handled. You can save this object for later use and invoke + * `respond` or `passThrough` again in order to change how a matched request is handled. + */ +angular.mock.e2e = {}; +angular.mock.e2e.$httpBackendDecorator = + ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock]; + + +/** + * @ngdoc type + * @name $rootScope.Scope + * @module ngMock + * @description + * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These + * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when + * `ngMock` module is loaded. + * + * In addition to all the regular `Scope` methods, the following helper methods are available: + */ +angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) { + + var $rootScopePrototype = Object.getPrototypeOf($delegate); + + $rootScopePrototype.$countChildScopes = countChildScopes; + $rootScopePrototype.$countWatchers = countWatchers; + + return $delegate; + + // ------------------------------------------------------------------------------------------ // + + /** + * @ngdoc method + * @name $rootScope.Scope#$countChildScopes + * @module ngMock + * @description + * Counts all the direct and indirect child scopes of the current scope. + * + * The current scope is excluded from the count. The count includes all isolate child scopes. + * + * @returns {number} Total number of child scopes. + */ + function countChildScopes() { + // jshint validthis: true + var count = 0; // exclude the current scope + var pendingChildHeads = [this.$$childHead]; + var currentScope; + + while (pendingChildHeads.length) { + currentScope = pendingChildHeads.shift(); + + while (currentScope) { + count += 1; + pendingChildHeads.push(currentScope.$$childHead); + currentScope = currentScope.$$nextSibling; + } + } + + return count; + } + + + /** + * @ngdoc method + * @name $rootScope.Scope#$countWatchers + * @module ngMock + * @description + * Counts all the watchers of direct and indirect child scopes of the current scope. + * + * The watchers of the current scope are included in the count and so are all the watchers of + * isolate child scopes. + * + * @returns {number} Total number of watchers. + */ + function countWatchers() { + // jshint validthis: true + var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope + var pendingChildHeads = [this.$$childHead]; + var currentScope; + + while (pendingChildHeads.length) { + currentScope = pendingChildHeads.shift(); + + while (currentScope) { + count += currentScope.$$watchers ? currentScope.$$watchers.length : 0; + pendingChildHeads.push(currentScope.$$childHead); + currentScope = currentScope.$$nextSibling; + } + } + + return count; + } +}]; + + +!(function(jasmineOrMocha) { + + if (!jasmineOrMocha) { + return; + } + + var currentSpec = null, + injectorState = new InjectorState(), + annotatedFunctions = [], + wasInjectorCreated = function() { + return !!currentSpec; + }; + + angular.mock.$$annotate = angular.injector.$$annotate; + angular.injector.$$annotate = function(fn) { + if (typeof fn === 'function' && !fn.$inject) { + annotatedFunctions.push(fn); + } + return angular.mock.$$annotate.apply(this, arguments); + }; + + /** + * @ngdoc function + * @name angular.mock.module + * @description + * + * *NOTE*: This function is also published on window for easy access.
    + * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha + * + * This function registers a module configuration code. It collects the configuration information + * which will be used when the injector is created by {@link angular.mock.inject inject}. + * + * See {@link angular.mock.inject inject} for usage example + * + * @param {...(string|Function|Object)} fns any number of modules which are represented as string + * aliases or as anonymous module initialization functions. The modules are used to + * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an + * object literal is passed each key-value pair will be registered on the module via + * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate + * with the value on the injector. + */ + var module = window.module = angular.mock.module = function() { + var moduleFns = Array.prototype.slice.call(arguments, 0); + return wasInjectorCreated() ? workFn() : workFn; + ///////////////////// + function workFn() { + if (currentSpec.$injector) { + throw new Error('Injector already created, can not register a module!'); + } else { + var fn, modules = currentSpec.$modules || (currentSpec.$modules = []); + angular.forEach(moduleFns, function(module) { + if (angular.isObject(module) && !angular.isArray(module)) { + fn = ['$provide', function($provide) { + angular.forEach(module, function(value, key) { + $provide.value(key, value); + }); + }]; + } else { + fn = module; + } + if (currentSpec.$providerInjector) { + currentSpec.$providerInjector.invoke(fn); + } else { + modules.push(fn); + } + }); + } + } + }; + + module.$$beforeAllHook = (window.before || window.beforeAll); + module.$$afterAllHook = (window.after || window.afterAll); + + // purely for testing ngMock itself + module.$$currentSpec = function(to) { + if (arguments.length === 0) return to; + currentSpec = to; + }; + + /** + * @ngdoc function + * @name angular.mock.module.sharedInjector + * @description + * + * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha + * + * This function ensures a single injector will be used for all tests in a given describe context. + * This contrasts with the default behaviour where a new injector is created per test case. + * + * Use sharedInjector when you want to take advantage of Jasmine's `beforeAll()`, or mocha's + * `before()` methods. Call `module.sharedInjector()` before you setup any other hooks that + * will create (i.e call `module()`) or use (i.e call `inject()`) the injector. + * + * You cannot call `sharedInjector()` from within a context already using `sharedInjector()`. + * + * ## Example + * + * Typically beforeAll is used to make many assertions about a single operation. This can + * cut down test run-time as the test setup doesn't need to be re-run, and enabling focussed + * tests each with a single assertion. + * + * ```js + * describe("Deep Thought", function() { + * + * module.sharedInjector(); + * + * beforeAll(module("UltimateQuestion")); + * + * beforeAll(inject(function(DeepThought) { + * expect(DeepThought.answer).toBeUndefined(); + * DeepThought.generateAnswer(); + * })); + * + * it("has calculated the answer correctly", inject(function(DeepThought) { + * // Because of sharedInjector, we have access to the instance of the DeepThought service + * // that was provided to the beforeAll() hook. Therefore we can test the generated answer + * expect(DeepThought.answer).toBe(42); + * })); + * + * it("has calculated the answer within the expected time", inject(function(DeepThought) { + * expect(DeepThought.runTimeMillennia).toBeLessThan(8000); + * })); + * + * it("has double checked the answer", inject(function(DeepThought) { + * expect(DeepThought.absolutelySureItIsTheRightAnswer).toBe(true); + * })); + * + * }); + * + * ``` + */ + module.sharedInjector = function() { + if (!(module.$$beforeAllHook && module.$$afterAllHook)) { + throw Error("sharedInjector() cannot be used unless your test runner defines beforeAll/afterAll"); + } + + var initialized = false; + + module.$$beforeAllHook(function() { + if (injectorState.shared) { + injectorState.sharedError = Error("sharedInjector() cannot be called inside a context that has already called sharedInjector()"); + throw injectorState.sharedError; + } + initialized = true; + currentSpec = this; + injectorState.shared = true; + }); + + module.$$afterAllHook(function() { + if (initialized) { + injectorState = new InjectorState(); + module.$$cleanup(); + } else { + injectorState.sharedError = null; + } + }); + }; + + module.$$beforeEach = function() { + if (injectorState.shared && currentSpec && currentSpec != this) { + var state = currentSpec; + currentSpec = this; + angular.forEach(["$injector","$modules","$providerInjector", "$injectorStrict"], function(k) { + currentSpec[k] = state[k]; + state[k] = null; + }); + } else { + currentSpec = this; + originalRootElement = null; + annotatedFunctions = []; + } + }; + + module.$$afterEach = function() { + if (injectorState.cleanupAfterEach()) { + module.$$cleanup(); + } + }; + + module.$$cleanup = function() { + var injector = currentSpec.$injector; + + annotatedFunctions.forEach(function(fn) { + delete fn.$inject; + }); + + angular.forEach(currentSpec.$modules, function(module) { + if (module && module.$$hashKey) { + module.$$hashKey = undefined; + } + }); + + currentSpec.$injector = null; + currentSpec.$modules = null; + currentSpec.$providerInjector = null; + currentSpec = null; + + if (injector) { + // Ensure `$rootElement` is instantiated, before checking `originalRootElement` + var $rootElement = injector.get('$rootElement'); + var rootNode = $rootElement && $rootElement[0]; + var cleanUpNodes = !originalRootElement ? [] : [originalRootElement[0]]; + if (rootNode && (!originalRootElement || rootNode !== originalRootElement[0])) { + cleanUpNodes.push(rootNode); + } + angular.element.cleanData(cleanUpNodes); + + // Ensure `$destroy()` is available, before calling it + // (a mocked `$rootScope` might not implement it (or not even be an object at all)) + var $rootScope = injector.get('$rootScope'); + if ($rootScope && $rootScope.$destroy) $rootScope.$destroy(); + } + + // clean up jquery's fragment cache + angular.forEach(angular.element.fragments, function(val, key) { + delete angular.element.fragments[key]; + }); + + MockXhr.$$lastInstance = null; + + angular.forEach(angular.callbacks, function(val, key) { + delete angular.callbacks[key]; + }); + angular.callbacks.$$counter = 0; + }; + + (window.beforeEach || window.setup)(module.$$beforeEach); + (window.afterEach || window.teardown)(module.$$afterEach); + + /** + * @ngdoc function + * @name angular.mock.inject + * @description + * + * *NOTE*: This function is also published on window for easy access.
    + * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha + * + * The inject function wraps a function into an injectable function. The inject() creates new + * instance of {@link auto.$injector $injector} per test, which is then used for + * resolving references. + * + * + * ## Resolving References (Underscore Wrapping) + * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this + * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable + * that is declared in the scope of the `describe()` block. Since we would, most likely, want + * the variable to have the same name of the reference we have a problem, since the parameter + * to the `inject()` function would hide the outer variable. + * + * To help with this, the injected parameters can, optionally, be enclosed with underscores. + * These are ignored by the injector when the reference name is resolved. + * + * For example, the parameter `_myService_` would be resolved as the reference `myService`. + * Since it is available in the function body as _myService_, we can then assign it to a variable + * defined in an outer scope. + * + * ``` + * // Defined out reference variable outside + * var myService; + * + * // Wrap the parameter in underscores + * beforeEach( inject( function(_myService_){ + * myService = _myService_; + * })); + * + * // Use myService in a series of tests. + * it('makes use of myService', function() { + * myService.doStuff(); + * }); + * + * ``` + * + * See also {@link angular.mock.module angular.mock.module} + * + * ## Example + * Example of what a typical jasmine tests looks like with the inject method. + * ```js + * + * angular.module('myApplicationModule', []) + * .value('mode', 'app') + * .value('version', 'v1.0.1'); + * + * + * describe('MyApp', function() { + * + * // You need to load modules that you want to test, + * // it loads only the "ng" module by default. + * beforeEach(module('myApplicationModule')); + * + * + * // inject() is used to inject arguments of all given functions + * it('should provide a version', inject(function(mode, version) { + * expect(version).toEqual('v1.0.1'); + * expect(mode).toEqual('app'); + * })); + * + * + * // The inject and module method can also be used inside of the it or beforeEach + * it('should override a version and test the new version is injected', function() { + * // module() takes functions or strings (module aliases) + * module(function($provide) { + * $provide.value('version', 'overridden'); // override version here + * }); + * + * inject(function(version) { + * expect(version).toEqual('overridden'); + * }); + * }); + * }); + * + * ``` + * + * @param {...Function} fns any number of functions which will be injected using the injector. + */ + + + + var ErrorAddingDeclarationLocationStack = function(e, errorForStack) { + this.message = e.message; + this.name = e.name; + if (e.line) this.line = e.line; + if (e.sourceId) this.sourceId = e.sourceId; + if (e.stack && errorForStack) + this.stack = e.stack + '\n' + errorForStack.stack; + if (e.stackArray) this.stackArray = e.stackArray; + }; + ErrorAddingDeclarationLocationStack.prototype = Error.prototype; + + window.inject = angular.mock.inject = function() { + var blockFns = Array.prototype.slice.call(arguments, 0); + var errorForStack = new Error('Declaration Location'); + // IE10+ and PhanthomJS do not set stack trace information, until the error is thrown + if (!errorForStack.stack) { + try { + throw errorForStack; + } catch (e) {} + } + return wasInjectorCreated() ? workFn.call(currentSpec) : workFn; + ///////////////////// + function workFn() { + var modules = currentSpec.$modules || []; + var strictDi = !!currentSpec.$injectorStrict; + modules.unshift(['$injector', function($injector) { + currentSpec.$providerInjector = $injector; + }]); + modules.unshift('ngMock'); + modules.unshift('ng'); + var injector = currentSpec.$injector; + if (!injector) { + if (strictDi) { + // If strictDi is enabled, annotate the providerInjector blocks + angular.forEach(modules, function(moduleFn) { + if (typeof moduleFn === "function") { + angular.injector.$$annotate(moduleFn); + } + }); + } + injector = currentSpec.$injector = angular.injector(modules, strictDi); + currentSpec.$injectorStrict = strictDi; + } + for (var i = 0, ii = blockFns.length; i < ii; i++) { + if (currentSpec.$injectorStrict) { + // If the injector is strict / strictDi, and the spec wants to inject using automatic + // annotation, then annotate the function here. + injector.annotate(blockFns[i]); + } + try { + /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */ + injector.invoke(blockFns[i] || angular.noop, this); + /* jshint +W040 */ + } catch (e) { + if (e.stack && errorForStack) { + throw new ErrorAddingDeclarationLocationStack(e, errorForStack); + } + throw e; + } finally { + errorForStack = null; + } + } + } + }; + + + angular.mock.inject.strictDi = function(value) { + value = arguments.length ? !!value : true; + return wasInjectorCreated() ? workFn() : workFn; + + function workFn() { + if (value !== currentSpec.$injectorStrict) { + if (currentSpec.$injector) { + throw new Error('Injector already created, can not modify strict annotations'); + } else { + currentSpec.$injectorStrict = value; + } + } + } + }; + + function InjectorState() { + this.shared = false; + this.sharedError = null; + + this.cleanupAfterEach = function() { + return !this.shared || this.sharedError; + }; + } +})(window.jasmine || window.mocha); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-parse-ext.js b/src/main/resources/static/module/angular/angular-parse-ext.js new file mode 100644 index 0000000..42e1335 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-parse-ext.js @@ -0,0 +1,1271 @@ +/** + * @license AngularJS v1.5.8 + * (c) 2010-2016 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular) {'use strict'; + +/****************************************************** + * Generated file, do not modify * + * * + *****************************************************/ + +function IDS_Y(cp) { + if (0x0041 <= cp && cp <= 0x005A) return true; + if (0x0061 <= cp && cp <= 0x007A) return true; + if (cp === 0x00AA) return true; + if (cp === 0x00B5) return true; + if (cp === 0x00BA) return true; + if (0x00C0 <= cp && cp <= 0x00D6) return true; + if (0x00D8 <= cp && cp <= 0x00F6) return true; + if (0x00F8 <= cp && cp <= 0x02C1) return true; + if (0x02C6 <= cp && cp <= 0x02D1) return true; + if (0x02E0 <= cp && cp <= 0x02E4) return true; + if (cp === 0x02EC) return true; + if (cp === 0x02EE) return true; + if (0x0370 <= cp && cp <= 0x0374) return true; + if (0x0376 <= cp && cp <= 0x0377) return true; + if (0x037A <= cp && cp <= 0x037D) return true; + if (cp === 0x037F) return true; + if (cp === 0x0386) return true; + if (0x0388 <= cp && cp <= 0x038A) return true; + if (cp === 0x038C) return true; + if (0x038E <= cp && cp <= 0x03A1) return true; + if (0x03A3 <= cp && cp <= 0x03F5) return true; + if (0x03F7 <= cp && cp <= 0x0481) return true; + if (0x048A <= cp && cp <= 0x052F) return true; + if (0x0531 <= cp && cp <= 0x0556) return true; + if (cp === 0x0559) return true; + if (0x0561 <= cp && cp <= 0x0587) return true; + if (0x05D0 <= cp && cp <= 0x05EA) return true; + if (0x05F0 <= cp && cp <= 0x05F2) return true; + if (0x0620 <= cp && cp <= 0x064A) return true; + if (0x066E <= cp && cp <= 0x066F) return true; + if (0x0671 <= cp && cp <= 0x06D3) return true; + if (cp === 0x06D5) return true; + if (0x06E5 <= cp && cp <= 0x06E6) return true; + if (0x06EE <= cp && cp <= 0x06EF) return true; + if (0x06FA <= cp && cp <= 0x06FC) return true; + if (cp === 0x06FF) return true; + if (cp === 0x0710) return true; + if (0x0712 <= cp && cp <= 0x072F) return true; + if (0x074D <= cp && cp <= 0x07A5) return true; + if (cp === 0x07B1) return true; + if (0x07CA <= cp && cp <= 0x07EA) return true; + if (0x07F4 <= cp && cp <= 0x07F5) return true; + if (cp === 0x07FA) return true; + if (0x0800 <= cp && cp <= 0x0815) return true; + if (cp === 0x081A) return true; + if (cp === 0x0824) return true; + if (cp === 0x0828) return true; + if (0x0840 <= cp && cp <= 0x0858) return true; + if (0x08A0 <= cp && cp <= 0x08B4) return true; + if (0x0904 <= cp && cp <= 0x0939) return true; + if (cp === 0x093D) return true; + if (cp === 0x0950) return true; + if (0x0958 <= cp && cp <= 0x0961) return true; + if (0x0971 <= cp && cp <= 0x0980) return true; + if (0x0985 <= cp && cp <= 0x098C) return true; + if (0x098F <= cp && cp <= 0x0990) return true; + if (0x0993 <= cp && cp <= 0x09A8) return true; + if (0x09AA <= cp && cp <= 0x09B0) return true; + if (cp === 0x09B2) return true; + if (0x09B6 <= cp && cp <= 0x09B9) return true; + if (cp === 0x09BD) return true; + if (cp === 0x09CE) return true; + if (0x09DC <= cp && cp <= 0x09DD) return true; + if (0x09DF <= cp && cp <= 0x09E1) return true; + if (0x09F0 <= cp && cp <= 0x09F1) return true; + if (0x0A05 <= cp && cp <= 0x0A0A) return true; + if (0x0A0F <= cp && cp <= 0x0A10) return true; + if (0x0A13 <= cp && cp <= 0x0A28) return true; + if (0x0A2A <= cp && cp <= 0x0A30) return true; + if (0x0A32 <= cp && cp <= 0x0A33) return true; + if (0x0A35 <= cp && cp <= 0x0A36) return true; + if (0x0A38 <= cp && cp <= 0x0A39) return true; + if (0x0A59 <= cp && cp <= 0x0A5C) return true; + if (cp === 0x0A5E) return true; + if (0x0A72 <= cp && cp <= 0x0A74) return true; + if (0x0A85 <= cp && cp <= 0x0A8D) return true; + if (0x0A8F <= cp && cp <= 0x0A91) return true; + if (0x0A93 <= cp && cp <= 0x0AA8) return true; + if (0x0AAA <= cp && cp <= 0x0AB0) return true; + if (0x0AB2 <= cp && cp <= 0x0AB3) return true; + if (0x0AB5 <= cp && cp <= 0x0AB9) return true; + if (cp === 0x0ABD) return true; + if (cp === 0x0AD0) return true; + if (0x0AE0 <= cp && cp <= 0x0AE1) return true; + if (cp === 0x0AF9) return true; + if (0x0B05 <= cp && cp <= 0x0B0C) return true; + if (0x0B0F <= cp && cp <= 0x0B10) return true; + if (0x0B13 <= cp && cp <= 0x0B28) return true; + if (0x0B2A <= cp && cp <= 0x0B30) return true; + if (0x0B32 <= cp && cp <= 0x0B33) return true; + if (0x0B35 <= cp && cp <= 0x0B39) return true; + if (cp === 0x0B3D) return true; + if (0x0B5C <= cp && cp <= 0x0B5D) return true; + if (0x0B5F <= cp && cp <= 0x0B61) return true; + if (cp === 0x0B71) return true; + if (cp === 0x0B83) return true; + if (0x0B85 <= cp && cp <= 0x0B8A) return true; + if (0x0B8E <= cp && cp <= 0x0B90) return true; + if (0x0B92 <= cp && cp <= 0x0B95) return true; + if (0x0B99 <= cp && cp <= 0x0B9A) return true; + if (cp === 0x0B9C) return true; + if (0x0B9E <= cp && cp <= 0x0B9F) return true; + if (0x0BA3 <= cp && cp <= 0x0BA4) return true; + if (0x0BA8 <= cp && cp <= 0x0BAA) return true; + if (0x0BAE <= cp && cp <= 0x0BB9) return true; + if (cp === 0x0BD0) return true; + if (0x0C05 <= cp && cp <= 0x0C0C) return true; + if (0x0C0E <= cp && cp <= 0x0C10) return true; + if (0x0C12 <= cp && cp <= 0x0C28) return true; + if (0x0C2A <= cp && cp <= 0x0C39) return true; + if (cp === 0x0C3D) return true; + if (0x0C58 <= cp && cp <= 0x0C5A) return true; + if (0x0C60 <= cp && cp <= 0x0C61) return true; + if (0x0C85 <= cp && cp <= 0x0C8C) return true; + if (0x0C8E <= cp && cp <= 0x0C90) return true; + if (0x0C92 <= cp && cp <= 0x0CA8) return true; + if (0x0CAA <= cp && cp <= 0x0CB3) return true; + if (0x0CB5 <= cp && cp <= 0x0CB9) return true; + if (cp === 0x0CBD) return true; + if (cp === 0x0CDE) return true; + if (0x0CE0 <= cp && cp <= 0x0CE1) return true; + if (0x0CF1 <= cp && cp <= 0x0CF2) return true; + if (0x0D05 <= cp && cp <= 0x0D0C) return true; + if (0x0D0E <= cp && cp <= 0x0D10) return true; + if (0x0D12 <= cp && cp <= 0x0D3A) return true; + if (cp === 0x0D3D) return true; + if (cp === 0x0D4E) return true; + if (0x0D5F <= cp && cp <= 0x0D61) return true; + if (0x0D7A <= cp && cp <= 0x0D7F) return true; + if (0x0D85 <= cp && cp <= 0x0D96) return true; + if (0x0D9A <= cp && cp <= 0x0DB1) return true; + if (0x0DB3 <= cp && cp <= 0x0DBB) return true; + if (cp === 0x0DBD) return true; + if (0x0DC0 <= cp && cp <= 0x0DC6) return true; + if (0x0E01 <= cp && cp <= 0x0E30) return true; + if (0x0E32 <= cp && cp <= 0x0E33) return true; + if (0x0E40 <= cp && cp <= 0x0E46) return true; + if (0x0E81 <= cp && cp <= 0x0E82) return true; + if (cp === 0x0E84) return true; + if (0x0E87 <= cp && cp <= 0x0E88) return true; + if (cp === 0x0E8A) return true; + if (cp === 0x0E8D) return true; + if (0x0E94 <= cp && cp <= 0x0E97) return true; + if (0x0E99 <= cp && cp <= 0x0E9F) return true; + if (0x0EA1 <= cp && cp <= 0x0EA3) return true; + if (cp === 0x0EA5) return true; + if (cp === 0x0EA7) return true; + if (0x0EAA <= cp && cp <= 0x0EAB) return true; + if (0x0EAD <= cp && cp <= 0x0EB0) return true; + if (0x0EB2 <= cp && cp <= 0x0EB3) return true; + if (cp === 0x0EBD) return true; + if (0x0EC0 <= cp && cp <= 0x0EC4) return true; + if (cp === 0x0EC6) return true; + if (0x0EDC <= cp && cp <= 0x0EDF) return true; + if (cp === 0x0F00) return true; + if (0x0F40 <= cp && cp <= 0x0F47) return true; + if (0x0F49 <= cp && cp <= 0x0F6C) return true; + if (0x0F88 <= cp && cp <= 0x0F8C) return true; + if (0x1000 <= cp && cp <= 0x102A) return true; + if (cp === 0x103F) return true; + if (0x1050 <= cp && cp <= 0x1055) return true; + if (0x105A <= cp && cp <= 0x105D) return true; + if (cp === 0x1061) return true; + if (0x1065 <= cp && cp <= 0x1066) return true; + if (0x106E <= cp && cp <= 0x1070) return true; + if (0x1075 <= cp && cp <= 0x1081) return true; + if (cp === 0x108E) return true; + if (0x10A0 <= cp && cp <= 0x10C5) return true; + if (cp === 0x10C7) return true; + if (cp === 0x10CD) return true; + if (0x10D0 <= cp && cp <= 0x10FA) return true; + if (0x10FC <= cp && cp <= 0x1248) return true; + if (0x124A <= cp && cp <= 0x124D) return true; + if (0x1250 <= cp && cp <= 0x1256) return true; + if (cp === 0x1258) return true; + if (0x125A <= cp && cp <= 0x125D) return true; + if (0x1260 <= cp && cp <= 0x1288) return true; + if (0x128A <= cp && cp <= 0x128D) return true; + if (0x1290 <= cp && cp <= 0x12B0) return true; + if (0x12B2 <= cp && cp <= 0x12B5) return true; + if (0x12B8 <= cp && cp <= 0x12BE) return true; + if (cp === 0x12C0) return true; + if (0x12C2 <= cp && cp <= 0x12C5) return true; + if (0x12C8 <= cp && cp <= 0x12D6) return true; + if (0x12D8 <= cp && cp <= 0x1310) return true; + if (0x1312 <= cp && cp <= 0x1315) return true; + if (0x1318 <= cp && cp <= 0x135A) return true; + if (0x1380 <= cp && cp <= 0x138F) return true; + if (0x13A0 <= cp && cp <= 0x13F5) return true; + if (0x13F8 <= cp && cp <= 0x13FD) return true; + if (0x1401 <= cp && cp <= 0x166C) return true; + if (0x166F <= cp && cp <= 0x167F) return true; + if (0x1681 <= cp && cp <= 0x169A) return true; + if (0x16A0 <= cp && cp <= 0x16EA) return true; + if (0x16EE <= cp && cp <= 0x16F8) return true; + if (0x1700 <= cp && cp <= 0x170C) return true; + if (0x170E <= cp && cp <= 0x1711) return true; + if (0x1720 <= cp && cp <= 0x1731) return true; + if (0x1740 <= cp && cp <= 0x1751) return true; + if (0x1760 <= cp && cp <= 0x176C) return true; + if (0x176E <= cp && cp <= 0x1770) return true; + if (0x1780 <= cp && cp <= 0x17B3) return true; + if (cp === 0x17D7) return true; + if (cp === 0x17DC) return true; + if (0x1820 <= cp && cp <= 0x1877) return true; + if (0x1880 <= cp && cp <= 0x18A8) return true; + if (cp === 0x18AA) return true; + if (0x18B0 <= cp && cp <= 0x18F5) return true; + if (0x1900 <= cp && cp <= 0x191E) return true; + if (0x1950 <= cp && cp <= 0x196D) return true; + if (0x1970 <= cp && cp <= 0x1974) return true; + if (0x1980 <= cp && cp <= 0x19AB) return true; + if (0x19B0 <= cp && cp <= 0x19C9) return true; + if (0x1A00 <= cp && cp <= 0x1A16) return true; + if (0x1A20 <= cp && cp <= 0x1A54) return true; + if (cp === 0x1AA7) return true; + if (0x1B05 <= cp && cp <= 0x1B33) return true; + if (0x1B45 <= cp && cp <= 0x1B4B) return true; + if (0x1B83 <= cp && cp <= 0x1BA0) return true; + if (0x1BAE <= cp && cp <= 0x1BAF) return true; + if (0x1BBA <= cp && cp <= 0x1BE5) return true; + if (0x1C00 <= cp && cp <= 0x1C23) return true; + if (0x1C4D <= cp && cp <= 0x1C4F) return true; + if (0x1C5A <= cp && cp <= 0x1C7D) return true; + if (0x1CE9 <= cp && cp <= 0x1CEC) return true; + if (0x1CEE <= cp && cp <= 0x1CF1) return true; + if (0x1CF5 <= cp && cp <= 0x1CF6) return true; + if (0x1D00 <= cp && cp <= 0x1DBF) return true; + if (0x1E00 <= cp && cp <= 0x1F15) return true; + if (0x1F18 <= cp && cp <= 0x1F1D) return true; + if (0x1F20 <= cp && cp <= 0x1F45) return true; + if (0x1F48 <= cp && cp <= 0x1F4D) return true; + if (0x1F50 <= cp && cp <= 0x1F57) return true; + if (cp === 0x1F59) return true; + if (cp === 0x1F5B) return true; + if (cp === 0x1F5D) return true; + if (0x1F5F <= cp && cp <= 0x1F7D) return true; + if (0x1F80 <= cp && cp <= 0x1FB4) return true; + if (0x1FB6 <= cp && cp <= 0x1FBC) return true; + if (cp === 0x1FBE) return true; + if (0x1FC2 <= cp && cp <= 0x1FC4) return true; + if (0x1FC6 <= cp && cp <= 0x1FCC) return true; + if (0x1FD0 <= cp && cp <= 0x1FD3) return true; + if (0x1FD6 <= cp && cp <= 0x1FDB) return true; + if (0x1FE0 <= cp && cp <= 0x1FEC) return true; + if (0x1FF2 <= cp && cp <= 0x1FF4) return true; + if (0x1FF6 <= cp && cp <= 0x1FFC) return true; + if (cp === 0x2071) return true; + if (cp === 0x207F) return true; + if (0x2090 <= cp && cp <= 0x209C) return true; + if (cp === 0x2102) return true; + if (cp === 0x2107) return true; + if (0x210A <= cp && cp <= 0x2113) return true; + if (cp === 0x2115) return true; + if (0x2118 <= cp && cp <= 0x211D) return true; + if (cp === 0x2124) return true; + if (cp === 0x2126) return true; + if (cp === 0x2128) return true; + if (0x212A <= cp && cp <= 0x2139) return true; + if (0x213C <= cp && cp <= 0x213F) return true; + if (0x2145 <= cp && cp <= 0x2149) return true; + if (cp === 0x214E) return true; + if (0x2160 <= cp && cp <= 0x2188) return true; + if (0x2C00 <= cp && cp <= 0x2C2E) return true; + if (0x2C30 <= cp && cp <= 0x2C5E) return true; + if (0x2C60 <= cp && cp <= 0x2CE4) return true; + if (0x2CEB <= cp && cp <= 0x2CEE) return true; + if (0x2CF2 <= cp && cp <= 0x2CF3) return true; + if (0x2D00 <= cp && cp <= 0x2D25) return true; + if (cp === 0x2D27) return true; + if (cp === 0x2D2D) return true; + if (0x2D30 <= cp && cp <= 0x2D67) return true; + if (cp === 0x2D6F) return true; + if (0x2D80 <= cp && cp <= 0x2D96) return true; + if (0x2DA0 <= cp && cp <= 0x2DA6) return true; + if (0x2DA8 <= cp && cp <= 0x2DAE) return true; + if (0x2DB0 <= cp && cp <= 0x2DB6) return true; + if (0x2DB8 <= cp && cp <= 0x2DBE) return true; + if (0x2DC0 <= cp && cp <= 0x2DC6) return true; + if (0x2DC8 <= cp && cp <= 0x2DCE) return true; + if (0x2DD0 <= cp && cp <= 0x2DD6) return true; + if (0x2DD8 <= cp && cp <= 0x2DDE) return true; + if (0x3005 <= cp && cp <= 0x3007) return true; + if (0x3021 <= cp && cp <= 0x3029) return true; + if (0x3031 <= cp && cp <= 0x3035) return true; + if (0x3038 <= cp && cp <= 0x303C) return true; + if (0x3041 <= cp && cp <= 0x3096) return true; + if (0x309B <= cp && cp <= 0x309F) return true; + if (0x30A1 <= cp && cp <= 0x30FA) return true; + if (0x30FC <= cp && cp <= 0x30FF) return true; + if (0x3105 <= cp && cp <= 0x312D) return true; + if (0x3131 <= cp && cp <= 0x318E) return true; + if (0x31A0 <= cp && cp <= 0x31BA) return true; + if (0x31F0 <= cp && cp <= 0x31FF) return true; + if (0x3400 <= cp && cp <= 0x4DB5) return true; + if (0x4E00 <= cp && cp <= 0x9FD5) return true; + if (0xA000 <= cp && cp <= 0xA48C) return true; + if (0xA4D0 <= cp && cp <= 0xA4FD) return true; + if (0xA500 <= cp && cp <= 0xA60C) return true; + if (0xA610 <= cp && cp <= 0xA61F) return true; + if (0xA62A <= cp && cp <= 0xA62B) return true; + if (0xA640 <= cp && cp <= 0xA66E) return true; + if (0xA67F <= cp && cp <= 0xA69D) return true; + if (0xA6A0 <= cp && cp <= 0xA6EF) return true; + if (0xA717 <= cp && cp <= 0xA71F) return true; + if (0xA722 <= cp && cp <= 0xA788) return true; + if (0xA78B <= cp && cp <= 0xA7AD) return true; + if (0xA7B0 <= cp && cp <= 0xA7B7) return true; + if (0xA7F7 <= cp && cp <= 0xA801) return true; + if (0xA803 <= cp && cp <= 0xA805) return true; + if (0xA807 <= cp && cp <= 0xA80A) return true; + if (0xA80C <= cp && cp <= 0xA822) return true; + if (0xA840 <= cp && cp <= 0xA873) return true; + if (0xA882 <= cp && cp <= 0xA8B3) return true; + if (0xA8F2 <= cp && cp <= 0xA8F7) return true; + if (cp === 0xA8FB) return true; + if (cp === 0xA8FD) return true; + if (0xA90A <= cp && cp <= 0xA925) return true; + if (0xA930 <= cp && cp <= 0xA946) return true; + if (0xA960 <= cp && cp <= 0xA97C) return true; + if (0xA984 <= cp && cp <= 0xA9B2) return true; + if (cp === 0xA9CF) return true; + if (0xA9E0 <= cp && cp <= 0xA9E4) return true; + if (0xA9E6 <= cp && cp <= 0xA9EF) return true; + if (0xA9FA <= cp && cp <= 0xA9FE) return true; + if (0xAA00 <= cp && cp <= 0xAA28) return true; + if (0xAA40 <= cp && cp <= 0xAA42) return true; + if (0xAA44 <= cp && cp <= 0xAA4B) return true; + if (0xAA60 <= cp && cp <= 0xAA76) return true; + if (cp === 0xAA7A) return true; + if (0xAA7E <= cp && cp <= 0xAAAF) return true; + if (cp === 0xAAB1) return true; + if (0xAAB5 <= cp && cp <= 0xAAB6) return true; + if (0xAAB9 <= cp && cp <= 0xAABD) return true; + if (cp === 0xAAC0) return true; + if (cp === 0xAAC2) return true; + if (0xAADB <= cp && cp <= 0xAADD) return true; + if (0xAAE0 <= cp && cp <= 0xAAEA) return true; + if (0xAAF2 <= cp && cp <= 0xAAF4) return true; + if (0xAB01 <= cp && cp <= 0xAB06) return true; + if (0xAB09 <= cp && cp <= 0xAB0E) return true; + if (0xAB11 <= cp && cp <= 0xAB16) return true; + if (0xAB20 <= cp && cp <= 0xAB26) return true; + if (0xAB28 <= cp && cp <= 0xAB2E) return true; + if (0xAB30 <= cp && cp <= 0xAB5A) return true; + if (0xAB5C <= cp && cp <= 0xAB65) return true; + if (0xAB70 <= cp && cp <= 0xABE2) return true; + if (0xAC00 <= cp && cp <= 0xD7A3) return true; + if (0xD7B0 <= cp && cp <= 0xD7C6) return true; + if (0xD7CB <= cp && cp <= 0xD7FB) return true; + if (0xF900 <= cp && cp <= 0xFA6D) return true; + if (0xFA70 <= cp && cp <= 0xFAD9) return true; + if (0xFB00 <= cp && cp <= 0xFB06) return true; + if (0xFB13 <= cp && cp <= 0xFB17) return true; + if (cp === 0xFB1D) return true; + if (0xFB1F <= cp && cp <= 0xFB28) return true; + if (0xFB2A <= cp && cp <= 0xFB36) return true; + if (0xFB38 <= cp && cp <= 0xFB3C) return true; + if (cp === 0xFB3E) return true; + if (0xFB40 <= cp && cp <= 0xFB41) return true; + if (0xFB43 <= cp && cp <= 0xFB44) return true; + if (0xFB46 <= cp && cp <= 0xFBB1) return true; + if (0xFBD3 <= cp && cp <= 0xFD3D) return true; + if (0xFD50 <= cp && cp <= 0xFD8F) return true; + if (0xFD92 <= cp && cp <= 0xFDC7) return true; + if (0xFDF0 <= cp && cp <= 0xFDFB) return true; + if (0xFE70 <= cp && cp <= 0xFE74) return true; + if (0xFE76 <= cp && cp <= 0xFEFC) return true; + if (0xFF21 <= cp && cp <= 0xFF3A) return true; + if (0xFF41 <= cp && cp <= 0xFF5A) return true; + if (0xFF66 <= cp && cp <= 0xFFBE) return true; + if (0xFFC2 <= cp && cp <= 0xFFC7) return true; + if (0xFFCA <= cp && cp <= 0xFFCF) return true; + if (0xFFD2 <= cp && cp <= 0xFFD7) return true; + if (0xFFDA <= cp && cp <= 0xFFDC) return true; + if (0x10000 <= cp && cp <= 0x1000B) return true; + if (0x1000D <= cp && cp <= 0x10026) return true; + if (0x10028 <= cp && cp <= 0x1003A) return true; + if (0x1003C <= cp && cp <= 0x1003D) return true; + if (0x1003F <= cp && cp <= 0x1004D) return true; + if (0x10050 <= cp && cp <= 0x1005D) return true; + if (0x10080 <= cp && cp <= 0x100FA) return true; + if (0x10140 <= cp && cp <= 0x10174) return true; + if (0x10280 <= cp && cp <= 0x1029C) return true; + if (0x102A0 <= cp && cp <= 0x102D0) return true; + if (0x10300 <= cp && cp <= 0x1031F) return true; + if (0x10330 <= cp && cp <= 0x1034A) return true; + if (0x10350 <= cp && cp <= 0x10375) return true; + if (0x10380 <= cp && cp <= 0x1039D) return true; + if (0x103A0 <= cp && cp <= 0x103C3) return true; + if (0x103C8 <= cp && cp <= 0x103CF) return true; + if (0x103D1 <= cp && cp <= 0x103D5) return true; + if (0x10400 <= cp && cp <= 0x1049D) return true; + if (0x10500 <= cp && cp <= 0x10527) return true; + if (0x10530 <= cp && cp <= 0x10563) return true; + if (0x10600 <= cp && cp <= 0x10736) return true; + if (0x10740 <= cp && cp <= 0x10755) return true; + if (0x10760 <= cp && cp <= 0x10767) return true; + if (0x10800 <= cp && cp <= 0x10805) return true; + if (cp === 0x10808) return true; + if (0x1080A <= cp && cp <= 0x10835) return true; + if (0x10837 <= cp && cp <= 0x10838) return true; + if (cp === 0x1083C) return true; + if (0x1083F <= cp && cp <= 0x10855) return true; + if (0x10860 <= cp && cp <= 0x10876) return true; + if (0x10880 <= cp && cp <= 0x1089E) return true; + if (0x108E0 <= cp && cp <= 0x108F2) return true; + if (0x108F4 <= cp && cp <= 0x108F5) return true; + if (0x10900 <= cp && cp <= 0x10915) return true; + if (0x10920 <= cp && cp <= 0x10939) return true; + if (0x10980 <= cp && cp <= 0x109B7) return true; + if (0x109BE <= cp && cp <= 0x109BF) return true; + if (cp === 0x10A00) return true; + if (0x10A10 <= cp && cp <= 0x10A13) return true; + if (0x10A15 <= cp && cp <= 0x10A17) return true; + if (0x10A19 <= cp && cp <= 0x10A33) return true; + if (0x10A60 <= cp && cp <= 0x10A7C) return true; + if (0x10A80 <= cp && cp <= 0x10A9C) return true; + if (0x10AC0 <= cp && cp <= 0x10AC7) return true; + if (0x10AC9 <= cp && cp <= 0x10AE4) return true; + if (0x10B00 <= cp && cp <= 0x10B35) return true; + if (0x10B40 <= cp && cp <= 0x10B55) return true; + if (0x10B60 <= cp && cp <= 0x10B72) return true; + if (0x10B80 <= cp && cp <= 0x10B91) return true; + if (0x10C00 <= cp && cp <= 0x10C48) return true; + if (0x10C80 <= cp && cp <= 0x10CB2) return true; + if (0x10CC0 <= cp && cp <= 0x10CF2) return true; + if (0x11003 <= cp && cp <= 0x11037) return true; + if (0x11083 <= cp && cp <= 0x110AF) return true; + if (0x110D0 <= cp && cp <= 0x110E8) return true; + if (0x11103 <= cp && cp <= 0x11126) return true; + if (0x11150 <= cp && cp <= 0x11172) return true; + if (cp === 0x11176) return true; + if (0x11183 <= cp && cp <= 0x111B2) return true; + if (0x111C1 <= cp && cp <= 0x111C4) return true; + if (cp === 0x111DA) return true; + if (cp === 0x111DC) return true; + if (0x11200 <= cp && cp <= 0x11211) return true; + if (0x11213 <= cp && cp <= 0x1122B) return true; + if (0x11280 <= cp && cp <= 0x11286) return true; + if (cp === 0x11288) return true; + if (0x1128A <= cp && cp <= 0x1128D) return true; + if (0x1128F <= cp && cp <= 0x1129D) return true; + if (0x1129F <= cp && cp <= 0x112A8) return true; + if (0x112B0 <= cp && cp <= 0x112DE) return true; + if (0x11305 <= cp && cp <= 0x1130C) return true; + if (0x1130F <= cp && cp <= 0x11310) return true; + if (0x11313 <= cp && cp <= 0x11328) return true; + if (0x1132A <= cp && cp <= 0x11330) return true; + if (0x11332 <= cp && cp <= 0x11333) return true; + if (0x11335 <= cp && cp <= 0x11339) return true; + if (cp === 0x1133D) return true; + if (cp === 0x11350) return true; + if (0x1135D <= cp && cp <= 0x11361) return true; + if (0x11480 <= cp && cp <= 0x114AF) return true; + if (0x114C4 <= cp && cp <= 0x114C5) return true; + if (cp === 0x114C7) return true; + if (0x11580 <= cp && cp <= 0x115AE) return true; + if (0x115D8 <= cp && cp <= 0x115DB) return true; + if (0x11600 <= cp && cp <= 0x1162F) return true; + if (cp === 0x11644) return true; + if (0x11680 <= cp && cp <= 0x116AA) return true; + if (0x11700 <= cp && cp <= 0x11719) return true; + if (0x118A0 <= cp && cp <= 0x118DF) return true; + if (cp === 0x118FF) return true; + if (0x11AC0 <= cp && cp <= 0x11AF8) return true; + if (0x12000 <= cp && cp <= 0x12399) return true; + if (0x12400 <= cp && cp <= 0x1246E) return true; + if (0x12480 <= cp && cp <= 0x12543) return true; + if (0x13000 <= cp && cp <= 0x1342E) return true; + if (0x14400 <= cp && cp <= 0x14646) return true; + if (0x16800 <= cp && cp <= 0x16A38) return true; + if (0x16A40 <= cp && cp <= 0x16A5E) return true; + if (0x16AD0 <= cp && cp <= 0x16AED) return true; + if (0x16B00 <= cp && cp <= 0x16B2F) return true; + if (0x16B40 <= cp && cp <= 0x16B43) return true; + if (0x16B63 <= cp && cp <= 0x16B77) return true; + if (0x16B7D <= cp && cp <= 0x16B8F) return true; + if (0x16F00 <= cp && cp <= 0x16F44) return true; + if (cp === 0x16F50) return true; + if (0x16F93 <= cp && cp <= 0x16F9F) return true; + if (0x1B000 <= cp && cp <= 0x1B001) return true; + if (0x1BC00 <= cp && cp <= 0x1BC6A) return true; + if (0x1BC70 <= cp && cp <= 0x1BC7C) return true; + if (0x1BC80 <= cp && cp <= 0x1BC88) return true; + if (0x1BC90 <= cp && cp <= 0x1BC99) return true; + if (0x1D400 <= cp && cp <= 0x1D454) return true; + if (0x1D456 <= cp && cp <= 0x1D49C) return true; + if (0x1D49E <= cp && cp <= 0x1D49F) return true; + if (cp === 0x1D4A2) return true; + if (0x1D4A5 <= cp && cp <= 0x1D4A6) return true; + if (0x1D4A9 <= cp && cp <= 0x1D4AC) return true; + if (0x1D4AE <= cp && cp <= 0x1D4B9) return true; + if (cp === 0x1D4BB) return true; + if (0x1D4BD <= cp && cp <= 0x1D4C3) return true; + if (0x1D4C5 <= cp && cp <= 0x1D505) return true; + if (0x1D507 <= cp && cp <= 0x1D50A) return true; + if (0x1D50D <= cp && cp <= 0x1D514) return true; + if (0x1D516 <= cp && cp <= 0x1D51C) return true; + if (0x1D51E <= cp && cp <= 0x1D539) return true; + if (0x1D53B <= cp && cp <= 0x1D53E) return true; + if (0x1D540 <= cp && cp <= 0x1D544) return true; + if (cp === 0x1D546) return true; + if (0x1D54A <= cp && cp <= 0x1D550) return true; + if (0x1D552 <= cp && cp <= 0x1D6A5) return true; + if (0x1D6A8 <= cp && cp <= 0x1D6C0) return true; + if (0x1D6C2 <= cp && cp <= 0x1D6DA) return true; + if (0x1D6DC <= cp && cp <= 0x1D6FA) return true; + if (0x1D6FC <= cp && cp <= 0x1D714) return true; + if (0x1D716 <= cp && cp <= 0x1D734) return true; + if (0x1D736 <= cp && cp <= 0x1D74E) return true; + if (0x1D750 <= cp && cp <= 0x1D76E) return true; + if (0x1D770 <= cp && cp <= 0x1D788) return true; + if (0x1D78A <= cp && cp <= 0x1D7A8) return true; + if (0x1D7AA <= cp && cp <= 0x1D7C2) return true; + if (0x1D7C4 <= cp && cp <= 0x1D7CB) return true; + if (0x1E800 <= cp && cp <= 0x1E8C4) return true; + if (0x1EE00 <= cp && cp <= 0x1EE03) return true; + if (0x1EE05 <= cp && cp <= 0x1EE1F) return true; + if (0x1EE21 <= cp && cp <= 0x1EE22) return true; + if (cp === 0x1EE24) return true; + if (cp === 0x1EE27) return true; + if (0x1EE29 <= cp && cp <= 0x1EE32) return true; + if (0x1EE34 <= cp && cp <= 0x1EE37) return true; + if (cp === 0x1EE39) return true; + if (cp === 0x1EE3B) return true; + if (cp === 0x1EE42) return true; + if (cp === 0x1EE47) return true; + if (cp === 0x1EE49) return true; + if (cp === 0x1EE4B) return true; + if (0x1EE4D <= cp && cp <= 0x1EE4F) return true; + if (0x1EE51 <= cp && cp <= 0x1EE52) return true; + if (cp === 0x1EE54) return true; + if (cp === 0x1EE57) return true; + if (cp === 0x1EE59) return true; + if (cp === 0x1EE5B) return true; + if (cp === 0x1EE5D) return true; + if (cp === 0x1EE5F) return true; + if (0x1EE61 <= cp && cp <= 0x1EE62) return true; + if (cp === 0x1EE64) return true; + if (0x1EE67 <= cp && cp <= 0x1EE6A) return true; + if (0x1EE6C <= cp && cp <= 0x1EE72) return true; + if (0x1EE74 <= cp && cp <= 0x1EE77) return true; + if (0x1EE79 <= cp && cp <= 0x1EE7C) return true; + if (cp === 0x1EE7E) return true; + if (0x1EE80 <= cp && cp <= 0x1EE89) return true; + if (0x1EE8B <= cp && cp <= 0x1EE9B) return true; + if (0x1EEA1 <= cp && cp <= 0x1EEA3) return true; + if (0x1EEA5 <= cp && cp <= 0x1EEA9) return true; + if (0x1EEAB <= cp && cp <= 0x1EEBB) return true; + if (0x20000 <= cp && cp <= 0x2A6D6) return true; + if (0x2A700 <= cp && cp <= 0x2B734) return true; + if (0x2B740 <= cp && cp <= 0x2B81D) return true; + if (0x2B820 <= cp && cp <= 0x2CEA1) return true; + if (0x2F800 <= cp && cp <= 0x2FA1D) return true; + return false; +} +function IDC_Y(cp) { + if (0x0030 <= cp && cp <= 0x0039) return true; + if (0x0041 <= cp && cp <= 0x005A) return true; + if (cp === 0x005F) return true; + if (0x0061 <= cp && cp <= 0x007A) return true; + if (cp === 0x00AA) return true; + if (cp === 0x00B5) return true; + if (cp === 0x00B7) return true; + if (cp === 0x00BA) return true; + if (0x00C0 <= cp && cp <= 0x00D6) return true; + if (0x00D8 <= cp && cp <= 0x00F6) return true; + if (0x00F8 <= cp && cp <= 0x02C1) return true; + if (0x02C6 <= cp && cp <= 0x02D1) return true; + if (0x02E0 <= cp && cp <= 0x02E4) return true; + if (cp === 0x02EC) return true; + if (cp === 0x02EE) return true; + if (0x0300 <= cp && cp <= 0x0374) return true; + if (0x0376 <= cp && cp <= 0x0377) return true; + if (0x037A <= cp && cp <= 0x037D) return true; + if (cp === 0x037F) return true; + if (0x0386 <= cp && cp <= 0x038A) return true; + if (cp === 0x038C) return true; + if (0x038E <= cp && cp <= 0x03A1) return true; + if (0x03A3 <= cp && cp <= 0x03F5) return true; + if (0x03F7 <= cp && cp <= 0x0481) return true; + if (0x0483 <= cp && cp <= 0x0487) return true; + if (0x048A <= cp && cp <= 0x052F) return true; + if (0x0531 <= cp && cp <= 0x0556) return true; + if (cp === 0x0559) return true; + if (0x0561 <= cp && cp <= 0x0587) return true; + if (0x0591 <= cp && cp <= 0x05BD) return true; + if (cp === 0x05BF) return true; + if (0x05C1 <= cp && cp <= 0x05C2) return true; + if (0x05C4 <= cp && cp <= 0x05C5) return true; + if (cp === 0x05C7) return true; + if (0x05D0 <= cp && cp <= 0x05EA) return true; + if (0x05F0 <= cp && cp <= 0x05F2) return true; + if (0x0610 <= cp && cp <= 0x061A) return true; + if (0x0620 <= cp && cp <= 0x0669) return true; + if (0x066E <= cp && cp <= 0x06D3) return true; + if (0x06D5 <= cp && cp <= 0x06DC) return true; + if (0x06DF <= cp && cp <= 0x06E8) return true; + if (0x06EA <= cp && cp <= 0x06FC) return true; + if (cp === 0x06FF) return true; + if (0x0710 <= cp && cp <= 0x074A) return true; + if (0x074D <= cp && cp <= 0x07B1) return true; + if (0x07C0 <= cp && cp <= 0x07F5) return true; + if (cp === 0x07FA) return true; + if (0x0800 <= cp && cp <= 0x082D) return true; + if (0x0840 <= cp && cp <= 0x085B) return true; + if (0x08A0 <= cp && cp <= 0x08B4) return true; + if (0x08E3 <= cp && cp <= 0x0963) return true; + if (0x0966 <= cp && cp <= 0x096F) return true; + if (0x0971 <= cp && cp <= 0x0983) return true; + if (0x0985 <= cp && cp <= 0x098C) return true; + if (0x098F <= cp && cp <= 0x0990) return true; + if (0x0993 <= cp && cp <= 0x09A8) return true; + if (0x09AA <= cp && cp <= 0x09B0) return true; + if (cp === 0x09B2) return true; + if (0x09B6 <= cp && cp <= 0x09B9) return true; + if (0x09BC <= cp && cp <= 0x09C4) return true; + if (0x09C7 <= cp && cp <= 0x09C8) return true; + if (0x09CB <= cp && cp <= 0x09CE) return true; + if (cp === 0x09D7) return true; + if (0x09DC <= cp && cp <= 0x09DD) return true; + if (0x09DF <= cp && cp <= 0x09E3) return true; + if (0x09E6 <= cp && cp <= 0x09F1) return true; + if (0x0A01 <= cp && cp <= 0x0A03) return true; + if (0x0A05 <= cp && cp <= 0x0A0A) return true; + if (0x0A0F <= cp && cp <= 0x0A10) return true; + if (0x0A13 <= cp && cp <= 0x0A28) return true; + if (0x0A2A <= cp && cp <= 0x0A30) return true; + if (0x0A32 <= cp && cp <= 0x0A33) return true; + if (0x0A35 <= cp && cp <= 0x0A36) return true; + if (0x0A38 <= cp && cp <= 0x0A39) return true; + if (cp === 0x0A3C) return true; + if (0x0A3E <= cp && cp <= 0x0A42) return true; + if (0x0A47 <= cp && cp <= 0x0A48) return true; + if (0x0A4B <= cp && cp <= 0x0A4D) return true; + if (cp === 0x0A51) return true; + if (0x0A59 <= cp && cp <= 0x0A5C) return true; + if (cp === 0x0A5E) return true; + if (0x0A66 <= cp && cp <= 0x0A75) return true; + if (0x0A81 <= cp && cp <= 0x0A83) return true; + if (0x0A85 <= cp && cp <= 0x0A8D) return true; + if (0x0A8F <= cp && cp <= 0x0A91) return true; + if (0x0A93 <= cp && cp <= 0x0AA8) return true; + if (0x0AAA <= cp && cp <= 0x0AB0) return true; + if (0x0AB2 <= cp && cp <= 0x0AB3) return true; + if (0x0AB5 <= cp && cp <= 0x0AB9) return true; + if (0x0ABC <= cp && cp <= 0x0AC5) return true; + if (0x0AC7 <= cp && cp <= 0x0AC9) return true; + if (0x0ACB <= cp && cp <= 0x0ACD) return true; + if (cp === 0x0AD0) return true; + if (0x0AE0 <= cp && cp <= 0x0AE3) return true; + if (0x0AE6 <= cp && cp <= 0x0AEF) return true; + if (cp === 0x0AF9) return true; + if (0x0B01 <= cp && cp <= 0x0B03) return true; + if (0x0B05 <= cp && cp <= 0x0B0C) return true; + if (0x0B0F <= cp && cp <= 0x0B10) return true; + if (0x0B13 <= cp && cp <= 0x0B28) return true; + if (0x0B2A <= cp && cp <= 0x0B30) return true; + if (0x0B32 <= cp && cp <= 0x0B33) return true; + if (0x0B35 <= cp && cp <= 0x0B39) return true; + if (0x0B3C <= cp && cp <= 0x0B44) return true; + if (0x0B47 <= cp && cp <= 0x0B48) return true; + if (0x0B4B <= cp && cp <= 0x0B4D) return true; + if (0x0B56 <= cp && cp <= 0x0B57) return true; + if (0x0B5C <= cp && cp <= 0x0B5D) return true; + if (0x0B5F <= cp && cp <= 0x0B63) return true; + if (0x0B66 <= cp && cp <= 0x0B6F) return true; + if (cp === 0x0B71) return true; + if (0x0B82 <= cp && cp <= 0x0B83) return true; + if (0x0B85 <= cp && cp <= 0x0B8A) return true; + if (0x0B8E <= cp && cp <= 0x0B90) return true; + if (0x0B92 <= cp && cp <= 0x0B95) return true; + if (0x0B99 <= cp && cp <= 0x0B9A) return true; + if (cp === 0x0B9C) return true; + if (0x0B9E <= cp && cp <= 0x0B9F) return true; + if (0x0BA3 <= cp && cp <= 0x0BA4) return true; + if (0x0BA8 <= cp && cp <= 0x0BAA) return true; + if (0x0BAE <= cp && cp <= 0x0BB9) return true; + if (0x0BBE <= cp && cp <= 0x0BC2) return true; + if (0x0BC6 <= cp && cp <= 0x0BC8) return true; + if (0x0BCA <= cp && cp <= 0x0BCD) return true; + if (cp === 0x0BD0) return true; + if (cp === 0x0BD7) return true; + if (0x0BE6 <= cp && cp <= 0x0BEF) return true; + if (0x0C00 <= cp && cp <= 0x0C03) return true; + if (0x0C05 <= cp && cp <= 0x0C0C) return true; + if (0x0C0E <= cp && cp <= 0x0C10) return true; + if (0x0C12 <= cp && cp <= 0x0C28) return true; + if (0x0C2A <= cp && cp <= 0x0C39) return true; + if (0x0C3D <= cp && cp <= 0x0C44) return true; + if (0x0C46 <= cp && cp <= 0x0C48) return true; + if (0x0C4A <= cp && cp <= 0x0C4D) return true; + if (0x0C55 <= cp && cp <= 0x0C56) return true; + if (0x0C58 <= cp && cp <= 0x0C5A) return true; + if (0x0C60 <= cp && cp <= 0x0C63) return true; + if (0x0C66 <= cp && cp <= 0x0C6F) return true; + if (0x0C81 <= cp && cp <= 0x0C83) return true; + if (0x0C85 <= cp && cp <= 0x0C8C) return true; + if (0x0C8E <= cp && cp <= 0x0C90) return true; + if (0x0C92 <= cp && cp <= 0x0CA8) return true; + if (0x0CAA <= cp && cp <= 0x0CB3) return true; + if (0x0CB5 <= cp && cp <= 0x0CB9) return true; + if (0x0CBC <= cp && cp <= 0x0CC4) return true; + if (0x0CC6 <= cp && cp <= 0x0CC8) return true; + if (0x0CCA <= cp && cp <= 0x0CCD) return true; + if (0x0CD5 <= cp && cp <= 0x0CD6) return true; + if (cp === 0x0CDE) return true; + if (0x0CE0 <= cp && cp <= 0x0CE3) return true; + if (0x0CE6 <= cp && cp <= 0x0CEF) return true; + if (0x0CF1 <= cp && cp <= 0x0CF2) return true; + if (0x0D01 <= cp && cp <= 0x0D03) return true; + if (0x0D05 <= cp && cp <= 0x0D0C) return true; + if (0x0D0E <= cp && cp <= 0x0D10) return true; + if (0x0D12 <= cp && cp <= 0x0D3A) return true; + if (0x0D3D <= cp && cp <= 0x0D44) return true; + if (0x0D46 <= cp && cp <= 0x0D48) return true; + if (0x0D4A <= cp && cp <= 0x0D4E) return true; + if (cp === 0x0D57) return true; + if (0x0D5F <= cp && cp <= 0x0D63) return true; + if (0x0D66 <= cp && cp <= 0x0D6F) return true; + if (0x0D7A <= cp && cp <= 0x0D7F) return true; + if (0x0D82 <= cp && cp <= 0x0D83) return true; + if (0x0D85 <= cp && cp <= 0x0D96) return true; + if (0x0D9A <= cp && cp <= 0x0DB1) return true; + if (0x0DB3 <= cp && cp <= 0x0DBB) return true; + if (cp === 0x0DBD) return true; + if (0x0DC0 <= cp && cp <= 0x0DC6) return true; + if (cp === 0x0DCA) return true; + if (0x0DCF <= cp && cp <= 0x0DD4) return true; + if (cp === 0x0DD6) return true; + if (0x0DD8 <= cp && cp <= 0x0DDF) return true; + if (0x0DE6 <= cp && cp <= 0x0DEF) return true; + if (0x0DF2 <= cp && cp <= 0x0DF3) return true; + if (0x0E01 <= cp && cp <= 0x0E3A) return true; + if (0x0E40 <= cp && cp <= 0x0E4E) return true; + if (0x0E50 <= cp && cp <= 0x0E59) return true; + if (0x0E81 <= cp && cp <= 0x0E82) return true; + if (cp === 0x0E84) return true; + if (0x0E87 <= cp && cp <= 0x0E88) return true; + if (cp === 0x0E8A) return true; + if (cp === 0x0E8D) return true; + if (0x0E94 <= cp && cp <= 0x0E97) return true; + if (0x0E99 <= cp && cp <= 0x0E9F) return true; + if (0x0EA1 <= cp && cp <= 0x0EA3) return true; + if (cp === 0x0EA5) return true; + if (cp === 0x0EA7) return true; + if (0x0EAA <= cp && cp <= 0x0EAB) return true; + if (0x0EAD <= cp && cp <= 0x0EB9) return true; + if (0x0EBB <= cp && cp <= 0x0EBD) return true; + if (0x0EC0 <= cp && cp <= 0x0EC4) return true; + if (cp === 0x0EC6) return true; + if (0x0EC8 <= cp && cp <= 0x0ECD) return true; + if (0x0ED0 <= cp && cp <= 0x0ED9) return true; + if (0x0EDC <= cp && cp <= 0x0EDF) return true; + if (cp === 0x0F00) return true; + if (0x0F18 <= cp && cp <= 0x0F19) return true; + if (0x0F20 <= cp && cp <= 0x0F29) return true; + if (cp === 0x0F35) return true; + if (cp === 0x0F37) return true; + if (cp === 0x0F39) return true; + if (0x0F3E <= cp && cp <= 0x0F47) return true; + if (0x0F49 <= cp && cp <= 0x0F6C) return true; + if (0x0F71 <= cp && cp <= 0x0F84) return true; + if (0x0F86 <= cp && cp <= 0x0F97) return true; + if (0x0F99 <= cp && cp <= 0x0FBC) return true; + if (cp === 0x0FC6) return true; + if (0x1000 <= cp && cp <= 0x1049) return true; + if (0x1050 <= cp && cp <= 0x109D) return true; + if (0x10A0 <= cp && cp <= 0x10C5) return true; + if (cp === 0x10C7) return true; + if (cp === 0x10CD) return true; + if (0x10D0 <= cp && cp <= 0x10FA) return true; + if (0x10FC <= cp && cp <= 0x1248) return true; + if (0x124A <= cp && cp <= 0x124D) return true; + if (0x1250 <= cp && cp <= 0x1256) return true; + if (cp === 0x1258) return true; + if (0x125A <= cp && cp <= 0x125D) return true; + if (0x1260 <= cp && cp <= 0x1288) return true; + if (0x128A <= cp && cp <= 0x128D) return true; + if (0x1290 <= cp && cp <= 0x12B0) return true; + if (0x12B2 <= cp && cp <= 0x12B5) return true; + if (0x12B8 <= cp && cp <= 0x12BE) return true; + if (cp === 0x12C0) return true; + if (0x12C2 <= cp && cp <= 0x12C5) return true; + if (0x12C8 <= cp && cp <= 0x12D6) return true; + if (0x12D8 <= cp && cp <= 0x1310) return true; + if (0x1312 <= cp && cp <= 0x1315) return true; + if (0x1318 <= cp && cp <= 0x135A) return true; + if (0x135D <= cp && cp <= 0x135F) return true; + if (0x1369 <= cp && cp <= 0x1371) return true; + if (0x1380 <= cp && cp <= 0x138F) return true; + if (0x13A0 <= cp && cp <= 0x13F5) return true; + if (0x13F8 <= cp && cp <= 0x13FD) return true; + if (0x1401 <= cp && cp <= 0x166C) return true; + if (0x166F <= cp && cp <= 0x167F) return true; + if (0x1681 <= cp && cp <= 0x169A) return true; + if (0x16A0 <= cp && cp <= 0x16EA) return true; + if (0x16EE <= cp && cp <= 0x16F8) return true; + if (0x1700 <= cp && cp <= 0x170C) return true; + if (0x170E <= cp && cp <= 0x1714) return true; + if (0x1720 <= cp && cp <= 0x1734) return true; + if (0x1740 <= cp && cp <= 0x1753) return true; + if (0x1760 <= cp && cp <= 0x176C) return true; + if (0x176E <= cp && cp <= 0x1770) return true; + if (0x1772 <= cp && cp <= 0x1773) return true; + if (0x1780 <= cp && cp <= 0x17D3) return true; + if (cp === 0x17D7) return true; + if (0x17DC <= cp && cp <= 0x17DD) return true; + if (0x17E0 <= cp && cp <= 0x17E9) return true; + if (0x180B <= cp && cp <= 0x180D) return true; + if (0x1810 <= cp && cp <= 0x1819) return true; + if (0x1820 <= cp && cp <= 0x1877) return true; + if (0x1880 <= cp && cp <= 0x18AA) return true; + if (0x18B0 <= cp && cp <= 0x18F5) return true; + if (0x1900 <= cp && cp <= 0x191E) return true; + if (0x1920 <= cp && cp <= 0x192B) return true; + if (0x1930 <= cp && cp <= 0x193B) return true; + if (0x1946 <= cp && cp <= 0x196D) return true; + if (0x1970 <= cp && cp <= 0x1974) return true; + if (0x1980 <= cp && cp <= 0x19AB) return true; + if (0x19B0 <= cp && cp <= 0x19C9) return true; + if (0x19D0 <= cp && cp <= 0x19DA) return true; + if (0x1A00 <= cp && cp <= 0x1A1B) return true; + if (0x1A20 <= cp && cp <= 0x1A5E) return true; + if (0x1A60 <= cp && cp <= 0x1A7C) return true; + if (0x1A7F <= cp && cp <= 0x1A89) return true; + if (0x1A90 <= cp && cp <= 0x1A99) return true; + if (cp === 0x1AA7) return true; + if (0x1AB0 <= cp && cp <= 0x1ABD) return true; + if (0x1B00 <= cp && cp <= 0x1B4B) return true; + if (0x1B50 <= cp && cp <= 0x1B59) return true; + if (0x1B6B <= cp && cp <= 0x1B73) return true; + if (0x1B80 <= cp && cp <= 0x1BF3) return true; + if (0x1C00 <= cp && cp <= 0x1C37) return true; + if (0x1C40 <= cp && cp <= 0x1C49) return true; + if (0x1C4D <= cp && cp <= 0x1C7D) return true; + if (0x1CD0 <= cp && cp <= 0x1CD2) return true; + if (0x1CD4 <= cp && cp <= 0x1CF6) return true; + if (0x1CF8 <= cp && cp <= 0x1CF9) return true; + if (0x1D00 <= cp && cp <= 0x1DF5) return true; + if (0x1DFC <= cp && cp <= 0x1F15) return true; + if (0x1F18 <= cp && cp <= 0x1F1D) return true; + if (0x1F20 <= cp && cp <= 0x1F45) return true; + if (0x1F48 <= cp && cp <= 0x1F4D) return true; + if (0x1F50 <= cp && cp <= 0x1F57) return true; + if (cp === 0x1F59) return true; + if (cp === 0x1F5B) return true; + if (cp === 0x1F5D) return true; + if (0x1F5F <= cp && cp <= 0x1F7D) return true; + if (0x1F80 <= cp && cp <= 0x1FB4) return true; + if (0x1FB6 <= cp && cp <= 0x1FBC) return true; + if (cp === 0x1FBE) return true; + if (0x1FC2 <= cp && cp <= 0x1FC4) return true; + if (0x1FC6 <= cp && cp <= 0x1FCC) return true; + if (0x1FD0 <= cp && cp <= 0x1FD3) return true; + if (0x1FD6 <= cp && cp <= 0x1FDB) return true; + if (0x1FE0 <= cp && cp <= 0x1FEC) return true; + if (0x1FF2 <= cp && cp <= 0x1FF4) return true; + if (0x1FF6 <= cp && cp <= 0x1FFC) return true; + if (0x203F <= cp && cp <= 0x2040) return true; + if (cp === 0x2054) return true; + if (cp === 0x2071) return true; + if (cp === 0x207F) return true; + if (0x2090 <= cp && cp <= 0x209C) return true; + if (0x20D0 <= cp && cp <= 0x20DC) return true; + if (cp === 0x20E1) return true; + if (0x20E5 <= cp && cp <= 0x20F0) return true; + if (cp === 0x2102) return true; + if (cp === 0x2107) return true; + if (0x210A <= cp && cp <= 0x2113) return true; + if (cp === 0x2115) return true; + if (0x2118 <= cp && cp <= 0x211D) return true; + if (cp === 0x2124) return true; + if (cp === 0x2126) return true; + if (cp === 0x2128) return true; + if (0x212A <= cp && cp <= 0x2139) return true; + if (0x213C <= cp && cp <= 0x213F) return true; + if (0x2145 <= cp && cp <= 0x2149) return true; + if (cp === 0x214E) return true; + if (0x2160 <= cp && cp <= 0x2188) return true; + if (0x2C00 <= cp && cp <= 0x2C2E) return true; + if (0x2C30 <= cp && cp <= 0x2C5E) return true; + if (0x2C60 <= cp && cp <= 0x2CE4) return true; + if (0x2CEB <= cp && cp <= 0x2CF3) return true; + if (0x2D00 <= cp && cp <= 0x2D25) return true; + if (cp === 0x2D27) return true; + if (cp === 0x2D2D) return true; + if (0x2D30 <= cp && cp <= 0x2D67) return true; + if (cp === 0x2D6F) return true; + if (0x2D7F <= cp && cp <= 0x2D96) return true; + if (0x2DA0 <= cp && cp <= 0x2DA6) return true; + if (0x2DA8 <= cp && cp <= 0x2DAE) return true; + if (0x2DB0 <= cp && cp <= 0x2DB6) return true; + if (0x2DB8 <= cp && cp <= 0x2DBE) return true; + if (0x2DC0 <= cp && cp <= 0x2DC6) return true; + if (0x2DC8 <= cp && cp <= 0x2DCE) return true; + if (0x2DD0 <= cp && cp <= 0x2DD6) return true; + if (0x2DD8 <= cp && cp <= 0x2DDE) return true; + if (0x2DE0 <= cp && cp <= 0x2DFF) return true; + if (0x3005 <= cp && cp <= 0x3007) return true; + if (0x3021 <= cp && cp <= 0x302F) return true; + if (0x3031 <= cp && cp <= 0x3035) return true; + if (0x3038 <= cp && cp <= 0x303C) return true; + if (0x3041 <= cp && cp <= 0x3096) return true; + if (0x3099 <= cp && cp <= 0x309F) return true; + if (0x30A1 <= cp && cp <= 0x30FA) return true; + if (0x30FC <= cp && cp <= 0x30FF) return true; + if (0x3105 <= cp && cp <= 0x312D) return true; + if (0x3131 <= cp && cp <= 0x318E) return true; + if (0x31A0 <= cp && cp <= 0x31BA) return true; + if (0x31F0 <= cp && cp <= 0x31FF) return true; + if (0x3400 <= cp && cp <= 0x4DB5) return true; + if (0x4E00 <= cp && cp <= 0x9FD5) return true; + if (0xA000 <= cp && cp <= 0xA48C) return true; + if (0xA4D0 <= cp && cp <= 0xA4FD) return true; + if (0xA500 <= cp && cp <= 0xA60C) return true; + if (0xA610 <= cp && cp <= 0xA62B) return true; + if (0xA640 <= cp && cp <= 0xA66F) return true; + if (0xA674 <= cp && cp <= 0xA67D) return true; + if (0xA67F <= cp && cp <= 0xA6F1) return true; + if (0xA717 <= cp && cp <= 0xA71F) return true; + if (0xA722 <= cp && cp <= 0xA788) return true; + if (0xA78B <= cp && cp <= 0xA7AD) return true; + if (0xA7B0 <= cp && cp <= 0xA7B7) return true; + if (0xA7F7 <= cp && cp <= 0xA827) return true; + if (0xA840 <= cp && cp <= 0xA873) return true; + if (0xA880 <= cp && cp <= 0xA8C4) return true; + if (0xA8D0 <= cp && cp <= 0xA8D9) return true; + if (0xA8E0 <= cp && cp <= 0xA8F7) return true; + if (cp === 0xA8FB) return true; + if (cp === 0xA8FD) return true; + if (0xA900 <= cp && cp <= 0xA92D) return true; + if (0xA930 <= cp && cp <= 0xA953) return true; + if (0xA960 <= cp && cp <= 0xA97C) return true; + if (0xA980 <= cp && cp <= 0xA9C0) return true; + if (0xA9CF <= cp && cp <= 0xA9D9) return true; + if (0xA9E0 <= cp && cp <= 0xA9FE) return true; + if (0xAA00 <= cp && cp <= 0xAA36) return true; + if (0xAA40 <= cp && cp <= 0xAA4D) return true; + if (0xAA50 <= cp && cp <= 0xAA59) return true; + if (0xAA60 <= cp && cp <= 0xAA76) return true; + if (0xAA7A <= cp && cp <= 0xAAC2) return true; + if (0xAADB <= cp && cp <= 0xAADD) return true; + if (0xAAE0 <= cp && cp <= 0xAAEF) return true; + if (0xAAF2 <= cp && cp <= 0xAAF6) return true; + if (0xAB01 <= cp && cp <= 0xAB06) return true; + if (0xAB09 <= cp && cp <= 0xAB0E) return true; + if (0xAB11 <= cp && cp <= 0xAB16) return true; + if (0xAB20 <= cp && cp <= 0xAB26) return true; + if (0xAB28 <= cp && cp <= 0xAB2E) return true; + if (0xAB30 <= cp && cp <= 0xAB5A) return true; + if (0xAB5C <= cp && cp <= 0xAB65) return true; + if (0xAB70 <= cp && cp <= 0xABEA) return true; + if (0xABEC <= cp && cp <= 0xABED) return true; + if (0xABF0 <= cp && cp <= 0xABF9) return true; + if (0xAC00 <= cp && cp <= 0xD7A3) return true; + if (0xD7B0 <= cp && cp <= 0xD7C6) return true; + if (0xD7CB <= cp && cp <= 0xD7FB) return true; + if (0xF900 <= cp && cp <= 0xFA6D) return true; + if (0xFA70 <= cp && cp <= 0xFAD9) return true; + if (0xFB00 <= cp && cp <= 0xFB06) return true; + if (0xFB13 <= cp && cp <= 0xFB17) return true; + if (0xFB1D <= cp && cp <= 0xFB28) return true; + if (0xFB2A <= cp && cp <= 0xFB36) return true; + if (0xFB38 <= cp && cp <= 0xFB3C) return true; + if (cp === 0xFB3E) return true; + if (0xFB40 <= cp && cp <= 0xFB41) return true; + if (0xFB43 <= cp && cp <= 0xFB44) return true; + if (0xFB46 <= cp && cp <= 0xFBB1) return true; + if (0xFBD3 <= cp && cp <= 0xFD3D) return true; + if (0xFD50 <= cp && cp <= 0xFD8F) return true; + if (0xFD92 <= cp && cp <= 0xFDC7) return true; + if (0xFDF0 <= cp && cp <= 0xFDFB) return true; + if (0xFE00 <= cp && cp <= 0xFE0F) return true; + if (0xFE20 <= cp && cp <= 0xFE2F) return true; + if (0xFE33 <= cp && cp <= 0xFE34) return true; + if (0xFE4D <= cp && cp <= 0xFE4F) return true; + if (0xFE70 <= cp && cp <= 0xFE74) return true; + if (0xFE76 <= cp && cp <= 0xFEFC) return true; + if (0xFF10 <= cp && cp <= 0xFF19) return true; + if (0xFF21 <= cp && cp <= 0xFF3A) return true; + if (cp === 0xFF3F) return true; + if (0xFF41 <= cp && cp <= 0xFF5A) return true; + if (0xFF66 <= cp && cp <= 0xFFBE) return true; + if (0xFFC2 <= cp && cp <= 0xFFC7) return true; + if (0xFFCA <= cp && cp <= 0xFFCF) return true; + if (0xFFD2 <= cp && cp <= 0xFFD7) return true; + if (0xFFDA <= cp && cp <= 0xFFDC) return true; + if (0x10000 <= cp && cp <= 0x1000B) return true; + if (0x1000D <= cp && cp <= 0x10026) return true; + if (0x10028 <= cp && cp <= 0x1003A) return true; + if (0x1003C <= cp && cp <= 0x1003D) return true; + if (0x1003F <= cp && cp <= 0x1004D) return true; + if (0x10050 <= cp && cp <= 0x1005D) return true; + if (0x10080 <= cp && cp <= 0x100FA) return true; + if (0x10140 <= cp && cp <= 0x10174) return true; + if (cp === 0x101FD) return true; + if (0x10280 <= cp && cp <= 0x1029C) return true; + if (0x102A0 <= cp && cp <= 0x102D0) return true; + if (cp === 0x102E0) return true; + if (0x10300 <= cp && cp <= 0x1031F) return true; + if (0x10330 <= cp && cp <= 0x1034A) return true; + if (0x10350 <= cp && cp <= 0x1037A) return true; + if (0x10380 <= cp && cp <= 0x1039D) return true; + if (0x103A0 <= cp && cp <= 0x103C3) return true; + if (0x103C8 <= cp && cp <= 0x103CF) return true; + if (0x103D1 <= cp && cp <= 0x103D5) return true; + if (0x10400 <= cp && cp <= 0x1049D) return true; + if (0x104A0 <= cp && cp <= 0x104A9) return true; + if (0x10500 <= cp && cp <= 0x10527) return true; + if (0x10530 <= cp && cp <= 0x10563) return true; + if (0x10600 <= cp && cp <= 0x10736) return true; + if (0x10740 <= cp && cp <= 0x10755) return true; + if (0x10760 <= cp && cp <= 0x10767) return true; + if (0x10800 <= cp && cp <= 0x10805) return true; + if (cp === 0x10808) return true; + if (0x1080A <= cp && cp <= 0x10835) return true; + if (0x10837 <= cp && cp <= 0x10838) return true; + if (cp === 0x1083C) return true; + if (0x1083F <= cp && cp <= 0x10855) return true; + if (0x10860 <= cp && cp <= 0x10876) return true; + if (0x10880 <= cp && cp <= 0x1089E) return true; + if (0x108E0 <= cp && cp <= 0x108F2) return true; + if (0x108F4 <= cp && cp <= 0x108F5) return true; + if (0x10900 <= cp && cp <= 0x10915) return true; + if (0x10920 <= cp && cp <= 0x10939) return true; + if (0x10980 <= cp && cp <= 0x109B7) return true; + if (0x109BE <= cp && cp <= 0x109BF) return true; + if (0x10A00 <= cp && cp <= 0x10A03) return true; + if (0x10A05 <= cp && cp <= 0x10A06) return true; + if (0x10A0C <= cp && cp <= 0x10A13) return true; + if (0x10A15 <= cp && cp <= 0x10A17) return true; + if (0x10A19 <= cp && cp <= 0x10A33) return true; + if (0x10A38 <= cp && cp <= 0x10A3A) return true; + if (cp === 0x10A3F) return true; + if (0x10A60 <= cp && cp <= 0x10A7C) return true; + if (0x10A80 <= cp && cp <= 0x10A9C) return true; + if (0x10AC0 <= cp && cp <= 0x10AC7) return true; + if (0x10AC9 <= cp && cp <= 0x10AE6) return true; + if (0x10B00 <= cp && cp <= 0x10B35) return true; + if (0x10B40 <= cp && cp <= 0x10B55) return true; + if (0x10B60 <= cp && cp <= 0x10B72) return true; + if (0x10B80 <= cp && cp <= 0x10B91) return true; + if (0x10C00 <= cp && cp <= 0x10C48) return true; + if (0x10C80 <= cp && cp <= 0x10CB2) return true; + if (0x10CC0 <= cp && cp <= 0x10CF2) return true; + if (0x11000 <= cp && cp <= 0x11046) return true; + if (0x11066 <= cp && cp <= 0x1106F) return true; + if (0x1107F <= cp && cp <= 0x110BA) return true; + if (0x110D0 <= cp && cp <= 0x110E8) return true; + if (0x110F0 <= cp && cp <= 0x110F9) return true; + if (0x11100 <= cp && cp <= 0x11134) return true; + if (0x11136 <= cp && cp <= 0x1113F) return true; + if (0x11150 <= cp && cp <= 0x11173) return true; + if (cp === 0x11176) return true; + if (0x11180 <= cp && cp <= 0x111C4) return true; + if (0x111CA <= cp && cp <= 0x111CC) return true; + if (0x111D0 <= cp && cp <= 0x111DA) return true; + if (cp === 0x111DC) return true; + if (0x11200 <= cp && cp <= 0x11211) return true; + if (0x11213 <= cp && cp <= 0x11237) return true; + if (0x11280 <= cp && cp <= 0x11286) return true; + if (cp === 0x11288) return true; + if (0x1128A <= cp && cp <= 0x1128D) return true; + if (0x1128F <= cp && cp <= 0x1129D) return true; + if (0x1129F <= cp && cp <= 0x112A8) return true; + if (0x112B0 <= cp && cp <= 0x112EA) return true; + if (0x112F0 <= cp && cp <= 0x112F9) return true; + if (0x11300 <= cp && cp <= 0x11303) return true; + if (0x11305 <= cp && cp <= 0x1130C) return true; + if (0x1130F <= cp && cp <= 0x11310) return true; + if (0x11313 <= cp && cp <= 0x11328) return true; + if (0x1132A <= cp && cp <= 0x11330) return true; + if (0x11332 <= cp && cp <= 0x11333) return true; + if (0x11335 <= cp && cp <= 0x11339) return true; + if (0x1133C <= cp && cp <= 0x11344) return true; + if (0x11347 <= cp && cp <= 0x11348) return true; + if (0x1134B <= cp && cp <= 0x1134D) return true; + if (cp === 0x11350) return true; + if (cp === 0x11357) return true; + if (0x1135D <= cp && cp <= 0x11363) return true; + if (0x11366 <= cp && cp <= 0x1136C) return true; + if (0x11370 <= cp && cp <= 0x11374) return true; + if (0x11480 <= cp && cp <= 0x114C5) return true; + if (cp === 0x114C7) return true; + if (0x114D0 <= cp && cp <= 0x114D9) return true; + if (0x11580 <= cp && cp <= 0x115B5) return true; + if (0x115B8 <= cp && cp <= 0x115C0) return true; + if (0x115D8 <= cp && cp <= 0x115DD) return true; + if (0x11600 <= cp && cp <= 0x11640) return true; + if (cp === 0x11644) return true; + if (0x11650 <= cp && cp <= 0x11659) return true; + if (0x11680 <= cp && cp <= 0x116B7) return true; + if (0x116C0 <= cp && cp <= 0x116C9) return true; + if (0x11700 <= cp && cp <= 0x11719) return true; + if (0x1171D <= cp && cp <= 0x1172B) return true; + if (0x11730 <= cp && cp <= 0x11739) return true; + if (0x118A0 <= cp && cp <= 0x118E9) return true; + if (cp === 0x118FF) return true; + if (0x11AC0 <= cp && cp <= 0x11AF8) return true; + if (0x12000 <= cp && cp <= 0x12399) return true; + if (0x12400 <= cp && cp <= 0x1246E) return true; + if (0x12480 <= cp && cp <= 0x12543) return true; + if (0x13000 <= cp && cp <= 0x1342E) return true; + if (0x14400 <= cp && cp <= 0x14646) return true; + if (0x16800 <= cp && cp <= 0x16A38) return true; + if (0x16A40 <= cp && cp <= 0x16A5E) return true; + if (0x16A60 <= cp && cp <= 0x16A69) return true; + if (0x16AD0 <= cp && cp <= 0x16AED) return true; + if (0x16AF0 <= cp && cp <= 0x16AF4) return true; + if (0x16B00 <= cp && cp <= 0x16B36) return true; + if (0x16B40 <= cp && cp <= 0x16B43) return true; + if (0x16B50 <= cp && cp <= 0x16B59) return true; + if (0x16B63 <= cp && cp <= 0x16B77) return true; + if (0x16B7D <= cp && cp <= 0x16B8F) return true; + if (0x16F00 <= cp && cp <= 0x16F44) return true; + if (0x16F50 <= cp && cp <= 0x16F7E) return true; + if (0x16F8F <= cp && cp <= 0x16F9F) return true; + if (0x1B000 <= cp && cp <= 0x1B001) return true; + if (0x1BC00 <= cp && cp <= 0x1BC6A) return true; + if (0x1BC70 <= cp && cp <= 0x1BC7C) return true; + if (0x1BC80 <= cp && cp <= 0x1BC88) return true; + if (0x1BC90 <= cp && cp <= 0x1BC99) return true; + if (0x1BC9D <= cp && cp <= 0x1BC9E) return true; + if (0x1D165 <= cp && cp <= 0x1D169) return true; + if (0x1D16D <= cp && cp <= 0x1D172) return true; + if (0x1D17B <= cp && cp <= 0x1D182) return true; + if (0x1D185 <= cp && cp <= 0x1D18B) return true; + if (0x1D1AA <= cp && cp <= 0x1D1AD) return true; + if (0x1D242 <= cp && cp <= 0x1D244) return true; + if (0x1D400 <= cp && cp <= 0x1D454) return true; + if (0x1D456 <= cp && cp <= 0x1D49C) return true; + if (0x1D49E <= cp && cp <= 0x1D49F) return true; + if (cp === 0x1D4A2) return true; + if (0x1D4A5 <= cp && cp <= 0x1D4A6) return true; + if (0x1D4A9 <= cp && cp <= 0x1D4AC) return true; + if (0x1D4AE <= cp && cp <= 0x1D4B9) return true; + if (cp === 0x1D4BB) return true; + if (0x1D4BD <= cp && cp <= 0x1D4C3) return true; + if (0x1D4C5 <= cp && cp <= 0x1D505) return true; + if (0x1D507 <= cp && cp <= 0x1D50A) return true; + if (0x1D50D <= cp && cp <= 0x1D514) return true; + if (0x1D516 <= cp && cp <= 0x1D51C) return true; + if (0x1D51E <= cp && cp <= 0x1D539) return true; + if (0x1D53B <= cp && cp <= 0x1D53E) return true; + if (0x1D540 <= cp && cp <= 0x1D544) return true; + if (cp === 0x1D546) return true; + if (0x1D54A <= cp && cp <= 0x1D550) return true; + if (0x1D552 <= cp && cp <= 0x1D6A5) return true; + if (0x1D6A8 <= cp && cp <= 0x1D6C0) return true; + if (0x1D6C2 <= cp && cp <= 0x1D6DA) return true; + if (0x1D6DC <= cp && cp <= 0x1D6FA) return true; + if (0x1D6FC <= cp && cp <= 0x1D714) return true; + if (0x1D716 <= cp && cp <= 0x1D734) return true; + if (0x1D736 <= cp && cp <= 0x1D74E) return true; + if (0x1D750 <= cp && cp <= 0x1D76E) return true; + if (0x1D770 <= cp && cp <= 0x1D788) return true; + if (0x1D78A <= cp && cp <= 0x1D7A8) return true; + if (0x1D7AA <= cp && cp <= 0x1D7C2) return true; + if (0x1D7C4 <= cp && cp <= 0x1D7CB) return true; + if (0x1D7CE <= cp && cp <= 0x1D7FF) return true; + if (0x1DA00 <= cp && cp <= 0x1DA36) return true; + if (0x1DA3B <= cp && cp <= 0x1DA6C) return true; + if (cp === 0x1DA75) return true; + if (cp === 0x1DA84) return true; + if (0x1DA9B <= cp && cp <= 0x1DA9F) return true; + if (0x1DAA1 <= cp && cp <= 0x1DAAF) return true; + if (0x1E800 <= cp && cp <= 0x1E8C4) return true; + if (0x1E8D0 <= cp && cp <= 0x1E8D6) return true; + if (0x1EE00 <= cp && cp <= 0x1EE03) return true; + if (0x1EE05 <= cp && cp <= 0x1EE1F) return true; + if (0x1EE21 <= cp && cp <= 0x1EE22) return true; + if (cp === 0x1EE24) return true; + if (cp === 0x1EE27) return true; + if (0x1EE29 <= cp && cp <= 0x1EE32) return true; + if (0x1EE34 <= cp && cp <= 0x1EE37) return true; + if (cp === 0x1EE39) return true; + if (cp === 0x1EE3B) return true; + if (cp === 0x1EE42) return true; + if (cp === 0x1EE47) return true; + if (cp === 0x1EE49) return true; + if (cp === 0x1EE4B) return true; + if (0x1EE4D <= cp && cp <= 0x1EE4F) return true; + if (0x1EE51 <= cp && cp <= 0x1EE52) return true; + if (cp === 0x1EE54) return true; + if (cp === 0x1EE57) return true; + if (cp === 0x1EE59) return true; + if (cp === 0x1EE5B) return true; + if (cp === 0x1EE5D) return true; + if (cp === 0x1EE5F) return true; + if (0x1EE61 <= cp && cp <= 0x1EE62) return true; + if (cp === 0x1EE64) return true; + if (0x1EE67 <= cp && cp <= 0x1EE6A) return true; + if (0x1EE6C <= cp && cp <= 0x1EE72) return true; + if (0x1EE74 <= cp && cp <= 0x1EE77) return true; + if (0x1EE79 <= cp && cp <= 0x1EE7C) return true; + if (cp === 0x1EE7E) return true; + if (0x1EE80 <= cp && cp <= 0x1EE89) return true; + if (0x1EE8B <= cp && cp <= 0x1EE9B) return true; + if (0x1EEA1 <= cp && cp <= 0x1EEA3) return true; + if (0x1EEA5 <= cp && cp <= 0x1EEA9) return true; + if (0x1EEAB <= cp && cp <= 0x1EEBB) return true; + if (0x20000 <= cp && cp <= 0x2A6D6) return true; + if (0x2A700 <= cp && cp <= 0x2B734) return true; + if (0x2B740 <= cp && cp <= 0x2B81D) return true; + if (0x2B820 <= cp && cp <= 0x2CEA1) return true; + if (0x2F800 <= cp && cp <= 0x2FA1D) return true; + if (0xE0100 <= cp && cp <= 0xE01EF) return true; + return false; +} + +/** + * @ngdoc module + * @name ngParseExt + * @packageName angular-parse-ext + * @description + * + * # ngParseExt + * + * The `ngParseExt` module provides functionality to allow Unicode characters in + * identifiers inside Angular expressions. + * + * + *
    + * + * This module allows the usage of any identifier that follows ES6 identifier naming convention + * to be used as an identifier in an Angular expression. ES6 delegates some of the identifier + * rules definition to Unicode, this module uses ES6 and Unicode 8.0 identifiers convention. + * + */ + +/* global angularParseExtModule: true, + IDS_Y, + IDC_Y +*/ + +function isValidIdentifierStart(ch, cp) { + return ch === '$' || + ch === '_' || + IDS_Y(cp); +} + +function isValidIdentifierContinue(ch, cp) { + return ch === '$' || + ch === '_' || + cp === 0x200C || // + cp === 0x200D || // + IDC_Y(cp); +} + +angular.module('ngParseExt', []) + .config(['$parseProvider', function($parseProvider) { + $parseProvider.setIdentifierFns(isValidIdentifierStart, isValidIdentifierContinue); + }]); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-parse-ext.min.js b/src/main/resources/static/module/angular/angular-parse-ext.min.js new file mode 100644 index 0000000..15c3ed8 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-parse-ext.min.js @@ -0,0 +1,49 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(f,c){'use strict';function d(b,a){return"$"===b||"_"===b||(65<=a&&90>=a||97<=a&&122>=a||170===a||181===a||186===a||192<=a&&214>=a||216<=a&&246>=a||248<=a&&705>=a||710<=a&&721>=a||736<=a&&740>=a||748===a||750===a||880<=a&&884>=a||886<=a&&887>=a||890<=a&&893>=a||895===a||902===a||904<=a&&906>=a||908===a||910<=a&&929>=a||931<=a&&1013>=a||1015<=a&&1153>=a||1162<=a&&1327>=a||1329<=a&&1366>=a||1369===a||1377<=a&&1415>=a||1488<=a&&1514>=a||1520<=a&&1522>=a||1568<=a&&1610>=a||1646<=a&&1647>=a|| +1649<=a&&1747>=a||1749===a||1765<=a&&1766>=a||1774<=a&&1775>=a||1786<=a&&1788>=a||1791===a||1808===a||1810<=a&&1839>=a||1869<=a&&1957>=a||1969===a||1994<=a&&2026>=a||2036<=a&&2037>=a||2042===a||2048<=a&&2069>=a||2074===a||2084===a||2088===a||2112<=a&&2136>=a||2208<=a&&2228>=a||2308<=a&&2361>=a||2365===a||2384===a||2392<=a&&2401>=a||2417<=a&&2432>=a||2437<=a&&2444>=a||2447<=a&&2448>=a||2451<=a&&2472>=a||2474<=a&&2480>=a||2482===a||2486<=a&&2489>=a||2493===a||2510===a||2524<=a&&2525>=a||2527<=a&&2529>= +a||2544<=a&&2545>=a||2565<=a&&2570>=a||2575<=a&&2576>=a||2579<=a&&2600>=a||2602<=a&&2608>=a||2610<=a&&2611>=a||2613<=a&&2614>=a||2616<=a&&2617>=a||2649<=a&&2652>=a||2654===a||2674<=a&&2676>=a||2693<=a&&2701>=a||2703<=a&&2705>=a||2707<=a&&2728>=a||2730<=a&&2736>=a||2738<=a&&2739>=a||2741<=a&&2745>=a||2749===a||2768===a||2784<=a&&2785>=a||2809===a||2821<=a&&2828>=a||2831<=a&&2832>=a||2835<=a&&2856>=a||2858<=a&&2864>=a||2866<=a&&2867>=a||2869<=a&&2873>=a||2877===a||2908<=a&&2909>=a||2911<=a&&2913>=a|| +2929===a||2947===a||2949<=a&&2954>=a||2958<=a&&2960>=a||2962<=a&&2965>=a||2969<=a&&2970>=a||2972===a||2974<=a&&2975>=a||2979<=a&&2980>=a||2984<=a&&2986>=a||2990<=a&&3001>=a||3024===a||3077<=a&&3084>=a||3086<=a&&3088>=a||3090<=a&&3112>=a||3114<=a&&3129>=a||3133===a||3160<=a&&3162>=a||3168<=a&&3169>=a||3205<=a&&3212>=a||3214<=a&&3216>=a||3218<=a&&3240>=a||3242<=a&&3251>=a||3253<=a&&3257>=a||3261===a||3294===a||3296<=a&&3297>=a||3313<=a&&3314>=a||3333<=a&&3340>=a||3342<=a&&3344>=a||3346<=a&&3386>=a|| +3389===a||3406===a||3423<=a&&3425>=a||3450<=a&&3455>=a||3461<=a&&3478>=a||3482<=a&&3505>=a||3507<=a&&3515>=a||3517===a||3520<=a&&3526>=a||3585<=a&&3632>=a||3634<=a&&3635>=a||3648<=a&&3654>=a||3713<=a&&3714>=a||3716===a||3719<=a&&3720>=a||3722===a||3725===a||3732<=a&&3735>=a||3737<=a&&3743>=a||3745<=a&&3747>=a||3749===a||3751===a||3754<=a&&3755>=a||3757<=a&&3760>=a||3762<=a&&3763>=a||3773===a||3776<=a&&3780>=a||3782===a||3804<=a&&3807>=a||3840===a||3904<=a&&3911>=a||3913<=a&&3948>=a||3976<=a&&3980>= +a||4096<=a&&4138>=a||4159===a||4176<=a&&4181>=a||4186<=a&&4189>=a||4193===a||4197<=a&&4198>=a||4206<=a&&4208>=a||4213<=a&&4225>=a||4238===a||4256<=a&&4293>=a||4295===a||4301===a||4304<=a&&4346>=a||4348<=a&&4680>=a||4682<=a&&4685>=a||4688<=a&&4694>=a||4696===a||4698<=a&&4701>=a||4704<=a&&4744>=a||4746<=a&&4749>=a||4752<=a&&4784>=a||4786<=a&&4789>=a||4792<=a&&4798>=a||4800===a||4802<=a&&4805>=a||4808<=a&&4822>=a||4824<=a&&4880>=a||4882<=a&&4885>=a||4888<=a&&4954>=a||4992<=a&&5007>=a||5024<=a&&5109>= +a||5112<=a&&5117>=a||5121<=a&&5740>=a||5743<=a&&5759>=a||5761<=a&&5786>=a||5792<=a&&5866>=a||5870<=a&&5880>=a||5888<=a&&5900>=a||5902<=a&&5905>=a||5920<=a&&5937>=a||5952<=a&&5969>=a||5984<=a&&5996>=a||5998<=a&&6E3>=a||6016<=a&&6067>=a||6103===a||6108===a||6176<=a&&6263>=a||6272<=a&&6312>=a||6314===a||6320<=a&&6389>=a||6400<=a&&6430>=a||6480<=a&&6509>=a||6512<=a&&6516>=a||6528<=a&&6571>=a||6576<=a&&6601>=a||6656<=a&&6678>=a||6688<=a&&6740>=a||6823===a||6917<=a&&6963>=a||6981<=a&&6987>=a||7043<=a&& +7072>=a||7086<=a&&7087>=a||7098<=a&&7141>=a||7168<=a&&7203>=a||7245<=a&&7247>=a||7258<=a&&7293>=a||7401<=a&&7404>=a||7406<=a&&7409>=a||7413<=a&&7414>=a||7424<=a&&7615>=a||7680<=a&&7957>=a||7960<=a&&7965>=a||7968<=a&&8005>=a||8008<=a&&8013>=a||8016<=a&&8023>=a||8025===a||8027===a||8029===a||8031<=a&&8061>=a||8064<=a&&8116>=a||8118<=a&&8124>=a||8126===a||8130<=a&&8132>=a||8134<=a&&8140>=a||8144<=a&&8147>=a||8150<=a&&8155>=a||8160<=a&&8172>=a||8178<=a&&8180>=a||8182<=a&&8188>=a||8305===a||8319===a|| +8336<=a&&8348>=a||8450===a||8455===a||8458<=a&&8467>=a||8469===a||8472<=a&&8477>=a||8484===a||8486===a||8488===a||8490<=a&&8505>=a||8508<=a&&8511>=a||8517<=a&&8521>=a||8526===a||8544<=a&&8584>=a||11264<=a&&11310>=a||11312<=a&&11358>=a||11360<=a&&11492>=a||11499<=a&&11502>=a||11506<=a&&11507>=a||11520<=a&&11557>=a||11559===a||11565===a||11568<=a&&11623>=a||11631===a||11648<=a&&11670>=a||11680<=a&&11686>=a||11688<=a&&11694>=a||11696<=a&&11702>=a||11704<=a&&11710>=a||11712<=a&&11718>=a||11720<=a&&11726>= +a||11728<=a&&11734>=a||11736<=a&&11742>=a||12293<=a&&12295>=a||12321<=a&&12329>=a||12337<=a&&12341>=a||12344<=a&&12348>=a||12353<=a&&12438>=a||12443<=a&&12447>=a||12449<=a&&12538>=a||12540<=a&&12543>=a||12549<=a&&12589>=a||12593<=a&&12686>=a||12704<=a&&12730>=a||12784<=a&&12799>=a||13312<=a&&19893>=a||19968<=a&&40917>=a||40960<=a&&42124>=a||42192<=a&&42237>=a||42240<=a&&42508>=a||42512<=a&&42527>=a||42538<=a&&42539>=a||42560<=a&&42606>=a||42623<=a&&42653>=a||42656<=a&&42735>=a||42775<=a&&42783>=a|| +42786<=a&&42888>=a||42891<=a&&42925>=a||42928<=a&&42935>=a||42999<=a&&43009>=a||43011<=a&&43013>=a||43015<=a&&43018>=a||43020<=a&&43042>=a||43072<=a&&43123>=a||43138<=a&&43187>=a||43250<=a&&43255>=a||43259===a||43261===a||43274<=a&&43301>=a||43312<=a&&43334>=a||43360<=a&&43388>=a||43396<=a&&43442>=a||43471===a||43488<=a&&43492>=a||43494<=a&&43503>=a||43514<=a&&43518>=a||43520<=a&&43560>=a||43584<=a&&43586>=a||43588<=a&&43595>=a||43616<=a&&43638>=a||43642===a||43646<=a&&43695>=a||43697===a||43701<= +a&&43702>=a||43705<=a&&43709>=a||43712===a||43714===a||43739<=a&&43741>=a||43744<=a&&43754>=a||43762<=a&&43764>=a||43777<=a&&43782>=a||43785<=a&&43790>=a||43793<=a&&43798>=a||43808<=a&&43814>=a||43816<=a&&43822>=a||43824<=a&&43866>=a||43868<=a&&43877>=a||43888<=a&&44002>=a||44032<=a&&55203>=a||55216<=a&&55238>=a||55243<=a&&55291>=a||63744<=a&&64109>=a||64112<=a&&64217>=a||64256<=a&&64262>=a||64275<=a&&64279>=a||64285===a||64287<=a&&64296>=a||64298<=a&&64310>=a||64312<=a&&64316>=a||64318===a||64320<= +a&&64321>=a||64323<=a&&64324>=a||64326<=a&&64433>=a||64467<=a&&64829>=a||64848<=a&&64911>=a||64914<=a&&64967>=a||65008<=a&&65019>=a||65136<=a&&65140>=a||65142<=a&&65276>=a||65313<=a&&65338>=a||65345<=a&&65370>=a||65382<=a&&65470>=a||65474<=a&&65479>=a||65482<=a&&65487>=a||65490<=a&&65495>=a||65498<=a&&65500>=a||65536<=a&&65547>=a||65549<=a&&65574>=a||65576<=a&&65594>=a||65596<=a&&65597>=a||65599<=a&&65613>=a||65616<=a&&65629>=a||65664<=a&&65786>=a||65856<=a&&65908>=a||66176<=a&&66204>=a||66208<=a&& +66256>=a||66304<=a&&66335>=a||66352<=a&&66378>=a||66384<=a&&66421>=a||66432<=a&&66461>=a||66464<=a&&66499>=a||66504<=a&&66511>=a||66513<=a&&66517>=a||66560<=a&&66717>=a||66816<=a&&66855>=a||66864<=a&&66915>=a||67072<=a&&67382>=a||67392<=a&&67413>=a||67424<=a&&67431>=a||67584<=a&&67589>=a||67592===a||67594<=a&&67637>=a||67639<=a&&67640>=a||67644===a||67647<=a&&67669>=a||67680<=a&&67702>=a||67712<=a&&67742>=a||67808<=a&&67826>=a||67828<=a&&67829>=a||67840<=a&&67861>=a||67872<=a&&67897>=a||67968<=a&& +68023>=a||68030<=a&&68031>=a||68096===a||68112<=a&&68115>=a||68117<=a&&68119>=a||68121<=a&&68147>=a||68192<=a&&68220>=a||68224<=a&&68252>=a||68288<=a&&68295>=a||68297<=a&&68324>=a||68352<=a&&68405>=a||68416<=a&&68437>=a||68448<=a&&68466>=a||68480<=a&&68497>=a||68608<=a&&68680>=a||68736<=a&&68786>=a||68800<=a&&68850>=a||69635<=a&&69687>=a||69763<=a&&69807>=a||69840<=a&&69864>=a||69891<=a&&69926>=a||69968<=a&&70002>=a||70006===a||70019<=a&&70066>=a||70081<=a&&70084>=a||70106===a||70108===a||70144<= +a&&70161>=a||70163<=a&&70187>=a||70272<=a&&70278>=a||70280===a||70282<=a&&70285>=a||70287<=a&&70301>=a||70303<=a&&70312>=a||70320<=a&&70366>=a||70405<=a&&70412>=a||70415<=a&&70416>=a||70419<=a&&70440>=a||70442<=a&&70448>=a||70450<=a&&70451>=a||70453<=a&&70457>=a||70461===a||70480===a||70493<=a&&70497>=a||70784<=a&&70831>=a||70852<=a&&70853>=a||70855===a||71040<=a&&71086>=a||71128<=a&&71131>=a||71168<=a&&71215>=a||71236===a||71296<=a&&71338>=a||71424<=a&&71449>=a||71840<=a&&71903>=a||71935===a||72384<= +a&&72440>=a||73728<=a&&74649>=a||74752<=a&&74862>=a||74880<=a&&75075>=a||77824<=a&&78894>=a||82944<=a&&83526>=a||92160<=a&&92728>=a||92736<=a&&92766>=a||92880<=a&&92909>=a||92928<=a&&92975>=a||92992<=a&&92995>=a||93027<=a&&93047>=a||93053<=a&&93071>=a||93952<=a&&94020>=a||94032===a||94099<=a&&94111>=a||110592<=a&&110593>=a||113664<=a&&113770>=a||113776<=a&&113788>=a||113792<=a&&113800>=a||113808<=a&&113817>=a||119808<=a&&119892>=a||119894<=a&&119964>=a||119966<=a&&119967>=a||119970===a||119973<=a&& +119974>=a||119977<=a&&119980>=a||119982<=a&&119993>=a||119995===a||119997<=a&&120003>=a||120005<=a&&120069>=a||120071<=a&&120074>=a||120077<=a&&120084>=a||120086<=a&&120092>=a||120094<=a&&120121>=a||120123<=a&&120126>=a||120128<=a&&120132>=a||120134===a||120138<=a&&120144>=a||120146<=a&&120485>=a||120488<=a&&120512>=a||120514<=a&&120538>=a||120540<=a&&120570>=a||120572<=a&&120596>=a||120598<=a&&120628>=a||120630<=a&&120654>=a||120656<=a&&120686>=a||120688<=a&&120712>=a||120714<=a&&120744>=a||120746<= +a&&120770>=a||120772<=a&&120779>=a||124928<=a&&125124>=a||126464<=a&&126467>=a||126469<=a&&126495>=a||126497<=a&&126498>=a||126500===a||126503===a||126505<=a&&126514>=a||126516<=a&&126519>=a||126521===a||126523===a||126530===a||126535===a||126537===a||126539===a||126541<=a&&126543>=a||126545<=a&&126546>=a||126548===a||126551===a||126553===a||126555===a||126557===a||126559===a||126561<=a&&126562>=a||126564===a||126567<=a&&126570>=a||126572<=a&&126578>=a||126580<=a&&126583>=a||126585<=a&&126588>=a|| +126590===a||126592<=a&&126601>=a||126603<=a&&126619>=a||126625<=a&&126627>=a||126629<=a&&126633>=a||126635<=a&&126651>=a||131072<=a&&173782>=a||173824<=a&&177972>=a||177984<=a&&178205>=a||178208<=a&&183969>=a||194560<=a&&195101>=a?!0:!1)}function e(b,a){return"$"===b||"_"===b||8204===a||8205===a||(48<=a&&57>=a||65<=a&&90>=a||95===a||97<=a&&122>=a||170===a||181===a||183===a||186===a||192<=a&&214>=a||216<=a&&246>=a||248<=a&&705>=a||710<=a&&721>=a||736<=a&&740>=a||748===a||750===a||768<=a&&884>=a||886<= +a&&887>=a||890<=a&&893>=a||895===a||902<=a&&906>=a||908===a||910<=a&&929>=a||931<=a&&1013>=a||1015<=a&&1153>=a||1155<=a&&1159>=a||1162<=a&&1327>=a||1329<=a&&1366>=a||1369===a||1377<=a&&1415>=a||1425<=a&&1469>=a||1471===a||1473<=a&&1474>=a||1476<=a&&1477>=a||1479===a||1488<=a&&1514>=a||1520<=a&&1522>=a||1552<=a&&1562>=a||1568<=a&&1641>=a||1646<=a&&1747>=a||1749<=a&&1756>=a||1759<=a&&1768>=a||1770<=a&&1788>=a||1791===a||1808<=a&&1866>=a||1869<=a&&1969>=a||1984<=a&&2037>=a||2042===a||2048<=a&&2093>= +a||2112<=a&&2139>=a||2208<=a&&2228>=a||2275<=a&&2403>=a||2406<=a&&2415>=a||2417<=a&&2435>=a||2437<=a&&2444>=a||2447<=a&&2448>=a||2451<=a&&2472>=a||2474<=a&&2480>=a||2482===a||2486<=a&&2489>=a||2492<=a&&2500>=a||2503<=a&&2504>=a||2507<=a&&2510>=a||2519===a||2524<=a&&2525>=a||2527<=a&&2531>=a||2534<=a&&2545>=a||2561<=a&&2563>=a||2565<=a&&2570>=a||2575<=a&&2576>=a||2579<=a&&2600>=a||2602<=a&&2608>=a||2610<=a&&2611>=a||2613<=a&&2614>=a||2616<=a&&2617>=a||2620===a||2622<=a&&2626>=a||2631<=a&&2632>=a|| +2635<=a&&2637>=a||2641===a||2649<=a&&2652>=a||2654===a||2662<=a&&2677>=a||2689<=a&&2691>=a||2693<=a&&2701>=a||2703<=a&&2705>=a||2707<=a&&2728>=a||2730<=a&&2736>=a||2738<=a&&2739>=a||2741<=a&&2745>=a||2748<=a&&2757>=a||2759<=a&&2761>=a||2763<=a&&2765>=a||2768===a||2784<=a&&2787>=a||2790<=a&&2799>=a||2809===a||2817<=a&&2819>=a||2821<=a&&2828>=a||2831<=a&&2832>=a||2835<=a&&2856>=a||2858<=a&&2864>=a||2866<=a&&2867>=a||2869<=a&&2873>=a||2876<=a&&2884>=a||2887<=a&&2888>=a||2891<=a&&2893>=a||2902<=a&&2903>= +a||2908<=a&&2909>=a||2911<=a&&2915>=a||2918<=a&&2927>=a||2929===a||2946<=a&&2947>=a||2949<=a&&2954>=a||2958<=a&&2960>=a||2962<=a&&2965>=a||2969<=a&&2970>=a||2972===a||2974<=a&&2975>=a||2979<=a&&2980>=a||2984<=a&&2986>=a||2990<=a&&3001>=a||3006<=a&&3010>=a||3014<=a&&3016>=a||3018<=a&&3021>=a||3024===a||3031===a||3046<=a&&3055>=a||3072<=a&&3075>=a||3077<=a&&3084>=a||3086<=a&&3088>=a||3090<=a&&3112>=a||3114<=a&&3129>=a||3133<=a&&3140>=a||3142<=a&&3144>=a||3146<=a&&3149>=a||3157<=a&&3158>=a||3160<=a&& +3162>=a||3168<=a&&3171>=a||3174<=a&&3183>=a||3201<=a&&3203>=a||3205<=a&&3212>=a||3214<=a&&3216>=a||3218<=a&&3240>=a||3242<=a&&3251>=a||3253<=a&&3257>=a||3260<=a&&3268>=a||3270<=a&&3272>=a||3274<=a&&3277>=a||3285<=a&&3286>=a||3294===a||3296<=a&&3299>=a||3302<=a&&3311>=a||3313<=a&&3314>=a||3329<=a&&3331>=a||3333<=a&&3340>=a||3342<=a&&3344>=a||3346<=a&&3386>=a||3389<=a&&3396>=a||3398<=a&&3400>=a||3402<=a&&3406>=a||3415===a||3423<=a&&3427>=a||3430<=a&&3439>=a||3450<=a&&3455>=a||3458<=a&&3459>=a||3461<= +a&&3478>=a||3482<=a&&3505>=a||3507<=a&&3515>=a||3517===a||3520<=a&&3526>=a||3530===a||3535<=a&&3540>=a||3542===a||3544<=a&&3551>=a||3558<=a&&3567>=a||3570<=a&&3571>=a||3585<=a&&3642>=a||3648<=a&&3662>=a||3664<=a&&3673>=a||3713<=a&&3714>=a||3716===a||3719<=a&&3720>=a||3722===a||3725===a||3732<=a&&3735>=a||3737<=a&&3743>=a||3745<=a&&3747>=a||3749===a||3751===a||3754<=a&&3755>=a||3757<=a&&3769>=a||3771<=a&&3773>=a||3776<=a&&3780>=a||3782===a||3784<=a&&3789>=a||3792<=a&&3801>=a||3804<=a&&3807>=a||3840=== +a||3864<=a&&3865>=a||3872<=a&&3881>=a||3893===a||3895===a||3897===a||3902<=a&&3911>=a||3913<=a&&3948>=a||3953<=a&&3972>=a||3974<=a&&3991>=a||3993<=a&&4028>=a||4038===a||4096<=a&&4169>=a||4176<=a&&4253>=a||4256<=a&&4293>=a||4295===a||4301===a||4304<=a&&4346>=a||4348<=a&&4680>=a||4682<=a&&4685>=a||4688<=a&&4694>=a||4696===a||4698<=a&&4701>=a||4704<=a&&4744>=a||4746<=a&&4749>=a||4752<=a&&4784>=a||4786<=a&&4789>=a||4792<=a&&4798>=a||4800===a||4802<=a&&4805>=a||4808<=a&&4822>=a||4824<=a&&4880>=a||4882<= +a&&4885>=a||4888<=a&&4954>=a||4957<=a&&4959>=a||4969<=a&&4977>=a||4992<=a&&5007>=a||5024<=a&&5109>=a||5112<=a&&5117>=a||5121<=a&&5740>=a||5743<=a&&5759>=a||5761<=a&&5786>=a||5792<=a&&5866>=a||5870<=a&&5880>=a||5888<=a&&5900>=a||5902<=a&&5908>=a||5920<=a&&5940>=a||5952<=a&&5971>=a||5984<=a&&5996>=a||5998<=a&&6E3>=a||6002<=a&&6003>=a||6016<=a&&6099>=a||6103===a||6108<=a&&6109>=a||6112<=a&&6121>=a||6155<=a&&6157>=a||6160<=a&&6169>=a||6176<=a&&6263>=a||6272<=a&&6314>=a||6320<=a&&6389>=a||6400<=a&&6430>= +a||6432<=a&&6443>=a||6448<=a&&6459>=a||6470<=a&&6509>=a||6512<=a&&6516>=a||6528<=a&&6571>=a||6576<=a&&6601>=a||6608<=a&&6618>=a||6656<=a&&6683>=a||6688<=a&&6750>=a||6752<=a&&6780>=a||6783<=a&&6793>=a||6800<=a&&6809>=a||6823===a||6832<=a&&6845>=a||6912<=a&&6987>=a||6992<=a&&7001>=a||7019<=a&&7027>=a||7040<=a&&7155>=a||7168<=a&&7223>=a||7232<=a&&7241>=a||7245<=a&&7293>=a||7376<=a&&7378>=a||7380<=a&&7414>=a||7416<=a&&7417>=a||7424<=a&&7669>=a||7676<=a&&7957>=a||7960<=a&&7965>=a||7968<=a&&8005>=a||8008<= +a&&8013>=a||8016<=a&&8023>=a||8025===a||8027===a||8029===a||8031<=a&&8061>=a||8064<=a&&8116>=a||8118<=a&&8124>=a||8126===a||8130<=a&&8132>=a||8134<=a&&8140>=a||8144<=a&&8147>=a||8150<=a&&8155>=a||8160<=a&&8172>=a||8178<=a&&8180>=a||8182<=a&&8188>=a||8255<=a&&8256>=a||8276===a||8305===a||8319===a||8336<=a&&8348>=a||8400<=a&&8412>=a||8417===a||8421<=a&&8432>=a||8450===a||8455===a||8458<=a&&8467>=a||8469===a||8472<=a&&8477>=a||8484===a||8486===a||8488===a||8490<=a&&8505>=a||8508<=a&&8511>=a||8517<=a&& +8521>=a||8526===a||8544<=a&&8584>=a||11264<=a&&11310>=a||11312<=a&&11358>=a||11360<=a&&11492>=a||11499<=a&&11507>=a||11520<=a&&11557>=a||11559===a||11565===a||11568<=a&&11623>=a||11631===a||11647<=a&&11670>=a||11680<=a&&11686>=a||11688<=a&&11694>=a||11696<=a&&11702>=a||11704<=a&&11710>=a||11712<=a&&11718>=a||11720<=a&&11726>=a||11728<=a&&11734>=a||11736<=a&&11742>=a||11744<=a&&11775>=a||12293<=a&&12295>=a||12321<=a&&12335>=a||12337<=a&&12341>=a||12344<=a&&12348>=a||12353<=a&&12438>=a||12441<=a&&12447>= +a||12449<=a&&12538>=a||12540<=a&&12543>=a||12549<=a&&12589>=a||12593<=a&&12686>=a||12704<=a&&12730>=a||12784<=a&&12799>=a||13312<=a&&19893>=a||19968<=a&&40917>=a||40960<=a&&42124>=a||42192<=a&&42237>=a||42240<=a&&42508>=a||42512<=a&&42539>=a||42560<=a&&42607>=a||42612<=a&&42621>=a||42623<=a&&42737>=a||42775<=a&&42783>=a||42786<=a&&42888>=a||42891<=a&&42925>=a||42928<=a&&42935>=a||42999<=a&&43047>=a||43072<=a&&43123>=a||43136<=a&&43204>=a||43216<=a&&43225>=a||43232<=a&&43255>=a||43259===a||43261=== +a||43264<=a&&43309>=a||43312<=a&&43347>=a||43360<=a&&43388>=a||43392<=a&&43456>=a||43471<=a&&43481>=a||43488<=a&&43518>=a||43520<=a&&43574>=a||43584<=a&&43597>=a||43600<=a&&43609>=a||43616<=a&&43638>=a||43642<=a&&43714>=a||43739<=a&&43741>=a||43744<=a&&43759>=a||43762<=a&&43766>=a||43777<=a&&43782>=a||43785<=a&&43790>=a||43793<=a&&43798>=a||43808<=a&&43814>=a||43816<=a&&43822>=a||43824<=a&&43866>=a||43868<=a&&43877>=a||43888<=a&&44010>=a||44012<=a&&44013>=a||44016<=a&&44025>=a||44032<=a&&55203>=a|| +55216<=a&&55238>=a||55243<=a&&55291>=a||63744<=a&&64109>=a||64112<=a&&64217>=a||64256<=a&&64262>=a||64275<=a&&64279>=a||64285<=a&&64296>=a||64298<=a&&64310>=a||64312<=a&&64316>=a||64318===a||64320<=a&&64321>=a||64323<=a&&64324>=a||64326<=a&&64433>=a||64467<=a&&64829>=a||64848<=a&&64911>=a||64914<=a&&64967>=a||65008<=a&&65019>=a||65024<=a&&65039>=a||65056<=a&&65071>=a||65075<=a&&65076>=a||65101<=a&&65103>=a||65136<=a&&65140>=a||65142<=a&&65276>=a||65296<=a&&65305>=a||65313<=a&&65338>=a||65343===a|| +65345<=a&&65370>=a||65382<=a&&65470>=a||65474<=a&&65479>=a||65482<=a&&65487>=a||65490<=a&&65495>=a||65498<=a&&65500>=a||65536<=a&&65547>=a||65549<=a&&65574>=a||65576<=a&&65594>=a||65596<=a&&65597>=a||65599<=a&&65613>=a||65616<=a&&65629>=a||65664<=a&&65786>=a||65856<=a&&65908>=a||66045===a||66176<=a&&66204>=a||66208<=a&&66256>=a||66272===a||66304<=a&&66335>=a||66352<=a&&66378>=a||66384<=a&&66426>=a||66432<=a&&66461>=a||66464<=a&&66499>=a||66504<=a&&66511>=a||66513<=a&&66517>=a||66560<=a&&66717>=a|| +66720<=a&&66729>=a||66816<=a&&66855>=a||66864<=a&&66915>=a||67072<=a&&67382>=a||67392<=a&&67413>=a||67424<=a&&67431>=a||67584<=a&&67589>=a||67592===a||67594<=a&&67637>=a||67639<=a&&67640>=a||67644===a||67647<=a&&67669>=a||67680<=a&&67702>=a||67712<=a&&67742>=a||67808<=a&&67826>=a||67828<=a&&67829>=a||67840<=a&&67861>=a||67872<=a&&67897>=a||67968<=a&&68023>=a||68030<=a&&68031>=a||68096<=a&&68099>=a||68101<=a&&68102>=a||68108<=a&&68115>=a||68117<=a&&68119>=a||68121<=a&&68147>=a||68152<=a&&68154>=a|| +68159===a||68192<=a&&68220>=a||68224<=a&&68252>=a||68288<=a&&68295>=a||68297<=a&&68326>=a||68352<=a&&68405>=a||68416<=a&&68437>=a||68448<=a&&68466>=a||68480<=a&&68497>=a||68608<=a&&68680>=a||68736<=a&&68786>=a||68800<=a&&68850>=a||69632<=a&&69702>=a||69734<=a&&69743>=a||69759<=a&&69818>=a||69840<=a&&69864>=a||69872<=a&&69881>=a||69888<=a&&69940>=a||69942<=a&&69951>=a||69968<=a&&70003>=a||70006===a||70016<=a&&70084>=a||70090<=a&&70092>=a||70096<=a&&70106>=a||70108===a||70144<=a&&70161>=a||70163<=a&& +70199>=a||70272<=a&&70278>=a||70280===a||70282<=a&&70285>=a||70287<=a&&70301>=a||70303<=a&&70312>=a||70320<=a&&70378>=a||70384<=a&&70393>=a||70400<=a&&70403>=a||70405<=a&&70412>=a||70415<=a&&70416>=a||70419<=a&&70440>=a||70442<=a&&70448>=a||70450<=a&&70451>=a||70453<=a&&70457>=a||70460<=a&&70468>=a||70471<=a&&70472>=a||70475<=a&&70477>=a||70480===a||70487===a||70493<=a&&70499>=a||70502<=a&&70508>=a||70512<=a&&70516>=a||70784<=a&&70853>=a||70855===a||70864<=a&&70873>=a||71040<=a&&71093>=a||71096<= +a&&71104>=a||71128<=a&&71133>=a||71168<=a&&71232>=a||71236===a||71248<=a&&71257>=a||71296<=a&&71351>=a||71360<=a&&71369>=a||71424<=a&&71449>=a||71453<=a&&71467>=a||71472<=a&&71481>=a||71840<=a&&71913>=a||71935===a||72384<=a&&72440>=a||73728<=a&&74649>=a||74752<=a&&74862>=a||74880<=a&&75075>=a||77824<=a&&78894>=a||82944<=a&&83526>=a||92160<=a&&92728>=a||92736<=a&&92766>=a||92768<=a&&92777>=a||92880<=a&&92909>=a||92912<=a&&92916>=a||92928<=a&&92982>=a||92992<=a&&92995>=a||93008<=a&&93017>=a||93027<= +a&&93047>=a||93053<=a&&93071>=a||93952<=a&&94020>=a||94032<=a&&94078>=a||94095<=a&&94111>=a||110592<=a&&110593>=a||113664<=a&&113770>=a||113776<=a&&113788>=a||113792<=a&&113800>=a||113808<=a&&113817>=a||113821<=a&&113822>=a||119141<=a&&119145>=a||119149<=a&&119154>=a||119163<=a&&119170>=a||119173<=a&&119179>=a||119210<=a&&119213>=a||119362<=a&&119364>=a||119808<=a&&119892>=a||119894<=a&&119964>=a||119966<=a&&119967>=a||119970===a||119973<=a&&119974>=a||119977<=a&&119980>=a||119982<=a&&119993>=a|| +119995===a||119997<=a&&120003>=a||120005<=a&&120069>=a||120071<=a&&120074>=a||120077<=a&&120084>=a||120086<=a&&120092>=a||120094<=a&&120121>=a||120123<=a&&120126>=a||120128<=a&&120132>=a||120134===a||120138<=a&&120144>=a||120146<=a&&120485>=a||120488<=a&&120512>=a||120514<=a&&120538>=a||120540<=a&&120570>=a||120572<=a&&120596>=a||120598<=a&&120628>=a||120630<=a&&120654>=a||120656<=a&&120686>=a||120688<=a&&120712>=a||120714<=a&&120744>=a||120746<=a&&120770>=a||120772<=a&&120779>=a||120782<=a&&120831>= +a||121344<=a&&121398>=a||121403<=a&&121452>=a||121461===a||121476===a||121499<=a&&121503>=a||121505<=a&&121519>=a||124928<=a&&125124>=a||125136<=a&&125142>=a||126464<=a&&126467>=a||126469<=a&&126495>=a||126497<=a&&126498>=a||126500===a||126503===a||126505<=a&&126514>=a||126516<=a&&126519>=a||126521===a||126523===a||126530===a||126535===a||126537===a||126539===a||126541<=a&&126543>=a||126545<=a&&126546>=a||126548===a||126551===a||126553===a||126555===a||126557===a||126559===a||126561<=a&&126562>=a|| +126564===a||126567<=a&&126570>=a||126572<=a&&126578>=a||126580<=a&&126583>=a||126585<=a&&126588>=a||126590===a||126592<=a&&126601>=a||126603<=a&&126619>=a||126625<=a&&126627>=a||126629<=a&&126633>=a||126635<=a&&126651>=a||131072<=a&&173782>=a||173824<=a&&177972>=a||177984<=a&&178205>=a||178208<=a&&183969>=a||194560<=a&&195101>=a||917760<=a&&917999>=a?!0:!1)}c.module("ngParseExt",[]).config(["$parseProvider",function(b){b.setIdentifierFns(d,e)}])})(window,window.angular); +//# sourceMappingURL=angular-parse-ext.min.js.map diff --git a/src/main/resources/static/module/angular/angular-parse-ext.min.js.map b/src/main/resources/static/module/angular/angular-parse-ext.min.js.map new file mode 100644 index 0000000..9f75d04 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-parse-ext.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-parse-ext.min.js", +"lineCount":48, +"mappings":"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", +"sources":["angular-parse-ext.js"], +"names":["window","angular","isValidIdentifierStart","ch","cp","isValidIdentifierContinue","module","config","$parseProvider","setIdentifierFns"] +} diff --git a/src/main/resources/static/module/angular/angular-resource.js b/src/main/resources/static/module/angular/angular-resource.js new file mode 100644 index 0000000..e8bb301 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-resource.js @@ -0,0 +1,863 @@ +/** + * @license AngularJS v1.5.8 + * (c) 2010-2016 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, angular) {'use strict'; + +var $resourceMinErr = angular.$$minErr('$resource'); + +// Helper functions and regex to lookup a dotted path on an object +// stopping at undefined/null. The path must be composed of ASCII +// identifiers (just like $parse) +var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/; + +function isValidDottedPath(path) { + return (path != null && path !== '' && path !== 'hasOwnProperty' && + MEMBER_NAME_REGEX.test('.' + path)); +} + +function lookupDottedPath(obj, path) { + if (!isValidDottedPath(path)) { + throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path); + } + var keys = path.split('.'); + for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) { + var key = keys[i]; + obj = (obj !== null) ? obj[key] : undefined; + } + return obj; +} + +/** + * Create a shallow copy of an object and clear other fields from the destination + */ +function shallowClearAndCopy(src, dst) { + dst = dst || {}; + + angular.forEach(dst, function(value, key) { + delete dst[key]; + }); + + for (var key in src) { + if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { + dst[key] = src[key]; + } + } + + return dst; +} + +/** + * @ngdoc module + * @name ngResource + * @description + * + * # ngResource + * + * The `ngResource` module provides interaction support with RESTful services + * via the $resource service. + * + * + *
    + * + * See {@link ngResource.$resourceProvider} and {@link ngResource.$resource} for usage. + */ + +/** + * @ngdoc provider + * @name $resourceProvider + * + * @description + * + * Use `$resourceProvider` to change the default behavior of the {@link ngResource.$resource} + * service. + * + * ## Dependencies + * Requires the {@link ngResource } module to be installed. + * + */ + +/** + * @ngdoc service + * @name $resource + * @requires $http + * @requires ng.$log + * @requires $q + * @requires ng.$timeout + * + * @description + * A factory which creates a resource object that lets you interact with + * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. + * + * The returned resource object has action methods which provide high-level behaviors without + * the need to interact with the low level {@link ng.$http $http} service. + * + * Requires the {@link ngResource `ngResource`} module to be installed. + * + * By default, trailing slashes will be stripped from the calculated URLs, + * which can pose problems with server backends that do not expect that + * behavior. This can be disabled by configuring the `$resourceProvider` like + * this: + * + * ```js + app.config(['$resourceProvider', function($resourceProvider) { + // Don't strip trailing slashes from calculated URLs + $resourceProvider.defaults.stripTrailingSlashes = false; + }]); + * ``` + * + * @param {string} url A parameterized URL template with parameters prefixed by `:` as in + * `/user/:username`. If you are using a URL with a port number (e.g. + * `http://example.com:8080/api`), it will be respected. + * + * If you are using a url with a suffix, just add the suffix, like this: + * `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')` + * or even `$resource('http://example.com/resource/:resource_id.:format')` + * If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be + * collapsed down to a single `.`. If you need this sequence to appear and not collapse then you + * can escape it with `/\.`. + * + * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in + * `actions` methods. If a parameter value is a function, it will be called every time + * a param value needs to be obtained for a request (unless the param was overridden). The function + * will be passed the current data value as an argument. + * + * Each key value in the parameter object is first bound to url template if present and then any + * excess keys are appended to the url search query after the `?`. + * + * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in + * URL `/path/greet?salutation=Hello`. + * + * If the parameter value is prefixed with `@`, then the value for that parameter will be + * extracted from the corresponding property on the `data` object (provided when calling a + * "non-GET" action method). + * For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of + * `someParam` will be `data.someProp`. + * Note that the parameter will be ignored, when calling a "GET" action method (i.e. an action + * method that does not accept a request body) + * + * @param {Object.=} actions Hash with declaration of custom actions that should extend + * the default set of resource actions. The declaration should be created in the format of {@link + * ng.$http#usage $http.config}: + * + * {action1: {method:?, params:?, isArray:?, headers:?, ...}, + * action2: {method:?, params:?, isArray:?, headers:?, ...}, + * ...} + * + * Where: + * + * - **`action`** – {string} – The name of action. This name becomes the name of the method on + * your resource object. + * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`, + * `DELETE`, `JSONP`, etc). + * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of + * the parameter value is a function, it will be called every time when a param value needs to + * be obtained for a request (unless the param was overridden). The function will be passed the + * current data value as an argument. + * - **`url`** – {string} – action specific `url` override. The url templating is supported just + * like for the resource-level urls. + * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, + * see `returns` section. + * - **`transformRequest`** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * request body and headers and returns its transformed (typically serialized) version. + * By default, transformRequest will contain one function that checks if the request data is + * an object and serializes to using `angular.toJson`. To prevent this behavior, set + * `transformRequest` to an empty array: `transformRequest: []` + * - **`transformResponse`** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * response body and headers and returns its transformed (typically deserialized) version. + * By default, transformResponse will contain one function that checks if the response looks + * like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, + * set `transformResponse` to an empty array: `transformResponse: []` + * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the + * GET request, otherwise if a cache instance built with + * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for + * caching. + * - **`timeout`** – `{number}` – timeout in milliseconds.
    + * **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are + * **not** supported in $resource, because the same value would be used for multiple requests. + * If you are looking for a way to cancel requests, you should use the `cancellable` option. + * - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call + * will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's + * return value. Calling `$cancelRequest()` for a non-cancellable or an already + * completed/cancelled request will have no effect.
    + * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the + * XHR object. See + * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5) + * for more information. + * - **`responseType`** - `{string}` - see + * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). + * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - + * `response` and `responseError`. Both `response` and `responseError` interceptors get called + * with `http response` object. See {@link ng.$http $http interceptors}. + * + * @param {Object} options Hash with custom settings that should extend the + * default `$resourceProvider` behavior. The supported options are: + * + * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing + * slashes from any calculated URL will be stripped. (Defaults to true.) + * - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be + * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value. + * This can be overwritten per action. (Defaults to false.) + * + * @returns {Object} A resource "class" object with methods for the default set of resource actions + * optionally extended with custom `actions`. The default set contains these actions: + * ```js + * { 'get': {method:'GET'}, + * 'save': {method:'POST'}, + * 'query': {method:'GET', isArray:true}, + * 'remove': {method:'DELETE'}, + * 'delete': {method:'DELETE'} }; + * ``` + * + * Calling these methods invoke an {@link ng.$http} with the specified http method, + * destination and parameters. When the data is returned from the server then the object is an + * instance of the resource class. The actions `save`, `remove` and `delete` are available on it + * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, + * read, update, delete) on server-side data like this: + * ```js + * var User = $resource('/user/:userId', {userId:'@id'}); + * var user = User.get({userId:123}, function() { + * user.abc = true; + * user.$save(); + * }); + * ``` + * + * It is important to realize that invoking a $resource object method immediately returns an + * empty reference (object or array depending on `isArray`). Once the data is returned from the + * server the existing reference is populated with the actual data. This is a useful trick since + * usually the resource is assigned to a model which is then rendered by the view. Having an empty + * object results in no rendering, once the data arrives from the server then the object is + * populated with the data and the view automatically re-renders itself showing the new data. This + * means that in most cases one never has to write a callback function for the action methods. + * + * The action methods on the class object or instance object can be invoked with the following + * parameters: + * + * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` + * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` + * - non-GET instance actions: `instance.$action([parameters], [success], [error])` + * + * + * Success callback is called with (value, responseHeaders) arguments, where the value is + * the populated resource instance or collection object. The error callback is called + * with (httpResponse) argument. + * + * Class actions return empty instance (with additional properties below). + * Instance actions return promise of the action. + * + * The Resource instances and collections have these additional properties: + * + * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this + * instance or collection. + * + * On success, the promise is resolved with the same resource instance or collection object, + * updated with data from server. This makes it easy to use in + * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view + * rendering until the resource(s) are loaded. + * + * On failure, the promise is rejected with the {@link ng.$http http response} object, without + * the `resource` property. + * + * If an interceptor object was provided, the promise will instead be resolved with the value + * returned by the interceptor. + * + * - `$resolved`: `true` after first server interaction is completed (either with success or + * rejection), `false` before that. Knowing if the Resource has been resolved is useful in + * data-binding. + * + * The Resource instances and collections have these additional methods: + * + * - `$cancelRequest`: If there is a cancellable, pending request related to the instance or + * collection, calling this method will abort the request. + * + * The Resource instances have these additional methods: + * + * - `toJSON`: It returns a simple object without any of the extra properties added as part of + * the Resource API. This object can be serialized through {@link angular.toJson} safely + * without attaching Angular-specific fields. Notice that `JSON.stringify` (and + * `angular.toJson`) automatically use this method when serializing a Resource instance + * (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior)). + * + * @example + * + * # Credit card resource + * + * ```js + // Define CreditCard class + var CreditCard = $resource('/user/:userId/card/:cardId', + {userId:123, cardId:'@id'}, { + charge: {method:'POST', params:{charge:true}} + }); + + // We can retrieve a collection from the server + var cards = CreditCard.query(function() { + // GET: /user/123/card + // server returns: [ {id:456, number:'1234', name:'Smith'} ]; + + var card = cards[0]; + // each item is an instance of CreditCard + expect(card instanceof CreditCard).toEqual(true); + card.name = "J. Smith"; + // non GET methods are mapped onto the instances + card.$save(); + // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} + // server returns: {id:456, number:'1234', name: 'J. Smith'}; + + // our custom method is mapped as well. + card.$charge({amount:9.99}); + // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} + }); + + // we can create an instance as well + var newCard = new CreditCard({number:'0123'}); + newCard.name = "Mike Smith"; + newCard.$save(); + // POST: /user/123/card {number:'0123', name:'Mike Smith'} + // server returns: {id:789, number:'0123', name: 'Mike Smith'}; + expect(newCard.id).toEqual(789); + * ``` + * + * The object returned from this function execution is a resource "class" which has "static" method + * for each action in the definition. + * + * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and + * `headers`. + * + * @example + * + * # User resource + * + * When the data is returned from the server then the object is an instance of the resource type and + * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD + * operations (create, read, update, delete) on server-side data. + + ```js + var User = $resource('/user/:userId', {userId:'@id'}); + User.get({userId:123}, function(user) { + user.abc = true; + user.$save(); + }); + ``` + * + * It's worth noting that the success callback for `get`, `query` and other methods gets passed + * in the response that came from the server as well as $http header getter function, so one + * could rewrite the above example and get access to http headers as: + * + ```js + var User = $resource('/user/:userId', {userId:'@id'}); + User.get({userId:123}, function(user, getResponseHeaders){ + user.abc = true; + user.$save(function(user, putResponseHeaders) { + //user => saved user object + //putResponseHeaders => $http header getter + }); + }); + ``` + * + * You can also access the raw `$http` promise via the `$promise` property on the object returned + * + ``` + var User = $resource('/user/:userId', {userId:'@id'}); + User.get({userId:123}) + .$promise.then(function(user) { + $scope.user = user; + }); + ``` + * + * @example + * + * # Creating a custom 'PUT' request + * + * In this example we create a custom method on our resource to make a PUT request + * ```js + * var app = angular.module('app', ['ngResource', 'ngRoute']); + * + * // Some APIs expect a PUT request in the format URL/object/ID + * // Here we are creating an 'update' method + * app.factory('Notes', ['$resource', function($resource) { + * return $resource('/notes/:id', null, + * { + * 'update': { method:'PUT' } + * }); + * }]); + * + * // In our controller we get the ID from the URL using ngRoute and $routeParams + * // We pass in $routeParams and our Notes factory along with $scope + * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', + function($scope, $routeParams, Notes) { + * // First get a note object from the factory + * var note = Notes.get({ id:$routeParams.id }); + * $id = note.id; + * + * // Now call update passing in the ID first then the object you are updating + * Notes.update({ id:$id }, note); + * + * // This will PUT /notes/ID with the note object in the request payload + * }]); + * ``` + * + * @example + * + * # Cancelling requests + * + * If an action's configuration specifies that it is cancellable, you can cancel the request related + * to an instance or collection (as long as it is a result of a "non-instance" call): + * + ```js + // ...defining the `Hotel` resource... + var Hotel = $resource('/api/hotel/:id', {id: '@id'}, { + // Let's make the `query()` method cancellable + query: {method: 'get', isArray: true, cancellable: true} + }); + + // ...somewhere in the PlanVacationController... + ... + this.onDestinationChanged = function onDestinationChanged(destination) { + // We don't care about any pending request for hotels + // in a different destination any more + this.availableHotels.$cancelRequest(); + + // Let's query for hotels in '' + // (calls: /api/hotel?location=) + this.availableHotels = Hotel.query({location: destination}); + }; + ``` + * + */ +angular.module('ngResource', ['ng']). + provider('$resource', function() { + var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/; + var provider = this; + + /** + * @ngdoc property + * @name $resourceProvider#defaults + * @description + * Object containing default options used when creating `$resource` instances. + * + * The default values satisfy a wide range of usecases, but you may choose to overwrite any of + * them to further customize your instances. The available properties are: + * + * - **stripTrailingSlashes** – `{boolean}` – If true, then the trailing slashes from any + * calculated URL will be stripped.
    + * (Defaults to true.) + * - **cancellable** – `{boolean}` – If true, the request made by a "non-instance" call will be + * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return + * value. For more details, see {@link ngResource.$resource}. This can be overwritten per + * resource class or action.
    + * (Defaults to false.) + * - **actions** - `{Object.}` - A hash with default actions declarations. Actions are + * high-level methods corresponding to RESTful actions/methods on resources. An action may + * specify what HTTP method to use, what URL to hit, if the return value will be a single + * object or a collection (array) of objects etc. For more details, see + * {@link ngResource.$resource}. The actions can also be enhanced or overwritten per resource + * class.
    + * The default actions are: + * ```js + * { + * get: {method: 'GET'}, + * save: {method: 'POST'}, + * query: {method: 'GET', isArray: true}, + * remove: {method: 'DELETE'}, + * delete: {method: 'DELETE'} + * } + * ``` + * + * #### Example + * + * For example, you can specify a new `update` action that uses the `PUT` HTTP verb: + * + * ```js + * angular. + * module('myApp'). + * config(['resourceProvider', function ($resourceProvider) { + * $resourceProvider.defaults.actions.update = { + * method: 'PUT' + * }; + * }); + * ``` + * + * Or you can even overwrite the whole `actions` list and specify your own: + * + * ```js + * angular. + * module('myApp'). + * config(['resourceProvider', function ($resourceProvider) { + * $resourceProvider.defaults.actions = { + * create: {method: 'POST'} + * get: {method: 'GET'}, + * getAll: {method: 'GET', isArray:true}, + * update: {method: 'PUT'}, + * delete: {method: 'DELETE'} + * }; + * }); + * ``` + * + */ + this.defaults = { + // Strip slashes by default + stripTrailingSlashes: true, + + // Make non-instance requests cancellable (via `$cancelRequest()`) + cancellable: false, + + // Default actions configuration + actions: { + 'get': {method: 'GET'}, + 'save': {method: 'POST'}, + 'query': {method: 'GET', isArray: true}, + 'remove': {method: 'DELETE'}, + 'delete': {method: 'DELETE'} + } + }; + + this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) { + + var noop = angular.noop, + forEach = angular.forEach, + extend = angular.extend, + copy = angular.copy, + isFunction = angular.isFunction; + + /** + * We need our custom method because encodeURIComponent is too aggressive and doesn't follow + * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set + * (pchar) allowed in path segments: + * segment = *pchar + * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + * pct-encoded = "%" HEXDIG HEXDIG + * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + * / "*" / "+" / "," / ";" / "=" + */ + function encodeUriSegment(val) { + return encodeUriQuery(val, true). + replace(/%26/gi, '&'). + replace(/%3D/gi, '='). + replace(/%2B/gi, '+'); + } + + + /** + * This method is intended for encoding *key* or *value* parts of query component. We need a + * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't + * have to be encoded per http://tools.ietf.org/html/rfc3986: + * query = *( pchar / "/" / "?" ) + * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * pct-encoded = "%" HEXDIG HEXDIG + * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + * / "*" / "+" / "," / ";" / "=" + */ + function encodeUriQuery(val, pctEncodeSpaces) { + return encodeURIComponent(val). + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); + } + + function Route(template, defaults) { + this.template = template; + this.defaults = extend({}, provider.defaults, defaults); + this.urlParams = {}; + } + + Route.prototype = { + setUrlParams: function(config, params, actionUrl) { + var self = this, + url = actionUrl || self.template, + val, + encodedVal, + protocolAndDomain = ''; + + var urlParams = self.urlParams = {}; + forEach(url.split(/\W/), function(param) { + if (param === 'hasOwnProperty') { + throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); + } + if (!(new RegExp("^\\d+$").test(param)) && param && + (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { + urlParams[param] = { + isQueryParamValue: (new RegExp("\\?.*=:" + param + "(?:\\W|$)")).test(url) + }; + } + }); + url = url.replace(/\\:/g, ':'); + url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) { + protocolAndDomain = match; + return ''; + }); + + params = params || {}; + forEach(self.urlParams, function(paramInfo, urlParam) { + val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; + if (angular.isDefined(val) && val !== null) { + if (paramInfo.isQueryParamValue) { + encodedVal = encodeUriQuery(val, true); + } else { + encodedVal = encodeUriSegment(val); + } + url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) { + return encodedVal + p1; + }); + } else { + url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match, + leadingSlashes, tail) { + if (tail.charAt(0) == '/') { + return tail; + } else { + return leadingSlashes + tail; + } + }); + } + }); + + // strip trailing slashes and set the url (unless this behavior is specifically disabled) + if (self.defaults.stripTrailingSlashes) { + url = url.replace(/\/+$/, '') || '/'; + } + + // then replace collapse `/.` if found in the last URL path segment before the query + // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` + url = url.replace(/\/\.(?=\w+($|\?))/, '.'); + // replace escaped `/\.` with `/.` + config.url = protocolAndDomain + url.replace(/\/\\\./, '/.'); + + + // set params - delegate param encoding to $http + forEach(params, function(value, key) { + if (!self.urlParams[key]) { + config.params = config.params || {}; + config.params[key] = value; + } + }); + } + }; + + + function resourceFactory(url, paramDefaults, actions, options) { + var route = new Route(url, options); + + actions = extend({}, provider.defaults.actions, actions); + + function extractParams(data, actionParams) { + var ids = {}; + actionParams = extend({}, paramDefaults, actionParams); + forEach(actionParams, function(value, key) { + if (isFunction(value)) { value = value(data); } + ids[key] = value && value.charAt && value.charAt(0) == '@' ? + lookupDottedPath(data, value.substr(1)) : value; + }); + return ids; + } + + function defaultResponseInterceptor(response) { + return response.resource; + } + + function Resource(value) { + shallowClearAndCopy(value || {}, this); + } + + Resource.prototype.toJSON = function() { + var data = extend({}, this); + delete data.$promise; + delete data.$resolved; + return data; + }; + + forEach(actions, function(action, name) { + var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); + var numericTimeout = action.timeout; + var cancellable = angular.isDefined(action.cancellable) ? action.cancellable : + (options && angular.isDefined(options.cancellable)) ? options.cancellable : + provider.defaults.cancellable; + + if (numericTimeout && !angular.isNumber(numericTimeout)) { + $log.debug('ngResource:\n' + + ' Only numeric values are allowed as `timeout`.\n' + + ' Promises are not supported in $resource, because the same value would ' + + 'be used for multiple requests. If you are looking for a way to cancel ' + + 'requests, you should use the `cancellable` option.'); + delete action.timeout; + numericTimeout = null; + } + + Resource[name] = function(a1, a2, a3, a4) { + var params = {}, data, success, error; + + /* jshint -W086 */ /* (purposefully fall through case statements) */ + switch (arguments.length) { + case 4: + error = a4; + success = a3; + //fallthrough + case 3: + case 2: + if (isFunction(a2)) { + if (isFunction(a1)) { + success = a1; + error = a2; + break; + } + + success = a2; + error = a3; + //fallthrough + } else { + params = a1; + data = a2; + success = a3; + break; + } + case 1: + if (isFunction(a1)) success = a1; + else if (hasBody) data = a1; + else params = a1; + break; + case 0: break; + default: + throw $resourceMinErr('badargs', + "Expected up to 4 arguments [params, data, success, error], got {0} arguments", + arguments.length); + } + /* jshint +W086 */ /* (purposefully fall through case statements) */ + + var isInstanceCall = this instanceof Resource; + var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); + var httpConfig = {}; + var responseInterceptor = action.interceptor && action.interceptor.response || + defaultResponseInterceptor; + var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || + undefined; + var timeoutDeferred; + var numericTimeoutPromise; + + forEach(action, function(value, key) { + switch (key) { + default: + httpConfig[key] = copy(value); + break; + case 'params': + case 'isArray': + case 'interceptor': + case 'cancellable': + break; + } + }); + + if (!isInstanceCall && cancellable) { + timeoutDeferred = $q.defer(); + httpConfig.timeout = timeoutDeferred.promise; + + if (numericTimeout) { + numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout); + } + } + + if (hasBody) httpConfig.data = data; + route.setUrlParams(httpConfig, + extend({}, extractParams(data, action.params || {}), params), + action.url); + + var promise = $http(httpConfig).then(function(response) { + var data = response.data; + + if (data) { + // Need to convert action.isArray to boolean in case it is undefined + // jshint -W018 + if (angular.isArray(data) !== (!!action.isArray)) { + throw $resourceMinErr('badcfg', + 'Error in resource configuration for action `{0}`. Expected response to ' + + 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object', + angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url); + } + // jshint +W018 + if (action.isArray) { + value.length = 0; + forEach(data, function(item) { + if (typeof item === "object") { + value.push(new Resource(item)); + } else { + // Valid JSON values may be string literals, and these should not be converted + // into objects. These items will not have access to the Resource prototype + // methods, but unfortunately there + value.push(item); + } + }); + } else { + var promise = value.$promise; // Save the promise + shallowClearAndCopy(data, value); + value.$promise = promise; // Restore the promise + } + } + response.resource = value; + + return response; + }, function(response) { + (error || noop)(response); + return $q.reject(response); + }); + + promise['finally'](function() { + value.$resolved = true; + if (!isInstanceCall && cancellable) { + value.$cancelRequest = angular.noop; + $timeout.cancel(numericTimeoutPromise); + timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null; + } + }); + + promise = promise.then( + function(response) { + var value = responseInterceptor(response); + (success || noop)(value, response.headers); + return value; + }, + responseErrorInterceptor); + + if (!isInstanceCall) { + // we are creating instance / collection + // - set the initial promise + // - return the instance / collection + value.$promise = promise; + value.$resolved = false; + if (cancellable) value.$cancelRequest = timeoutDeferred.resolve; + + return value; + } + + // instance call + return promise; + }; + + + Resource.prototype['$' + name] = function(params, success, error) { + if (isFunction(params)) { + error = success; success = params; params = {}; + } + var result = Resource[name].call(this, params, this, success, error); + return result.$promise || result; + }; + }); + + Resource.bind = function(additionalParamDefaults) { + return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); + }; + + return Resource; + } + + return resourceFactory; + }]; + }); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-resource.min.js b/src/main/resources/static/module/angular/angular-resource.min.js new file mode 100644 index 0000000..5001f29 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-resource.min.js @@ -0,0 +1,15 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(P,d){'use strict';function G(t,g){g=g||{};d.forEach(g,function(d,q){delete g[q]});for(var q in t)!t.hasOwnProperty(q)||"$"===q.charAt(0)&&"$"===q.charAt(1)||(g[q]=t[q]);return g}var z=d.$$minErr("$resource"),M=/^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;d.module("ngResource",["ng"]).provider("$resource",function(){var t=/^https?:\/\/[^\/]*/,g=this;this.defaults={stripTrailingSlashes:!0,cancellable:!1,actions:{get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"}, +"delete":{method:"DELETE"}}};this.$get=["$http","$log","$q","$timeout",function(q,L,H,I){function A(d,h){return encodeURIComponent(d).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,h?"%20":"+")}function B(d,h){this.template=d;this.defaults=v({},g.defaults,h);this.urlParams={}}function J(e,h,n,k){function b(a,c){var b={};c=v({},h,c);u(c,function(c,h){x(c)&&(c=c(a));var f;if(c&&c.charAt&&"@"==c.charAt(0)){f=a;var l=c.substr(1);if(null==l||""===l||"hasOwnProperty"=== +l||!M.test("."+l))throw z("badmember",l);for(var l=l.split("."),m=0,k=l.length;m + */ + /* global -ngRouteModule */ +var ngRouteModule = angular.module('ngRoute', ['ng']). + provider('$route', $RouteProvider), + $routeMinErr = angular.$$minErr('ngRoute'); + +/** + * @ngdoc provider + * @name $routeProvider + * + * @description + * + * Used for configuring routes. + * + * ## Example + * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. + * + * ## Dependencies + * Requires the {@link ngRoute `ngRoute`} module to be installed. + */ +function $RouteProvider() { + isArray = angular.isArray; + isObject = angular.isObject; + + function inherit(parent, extra) { + return angular.extend(Object.create(parent), extra); + } + + var routes = {}; + + /** + * @ngdoc method + * @name $routeProvider#when + * + * @param {string} path Route path (matched against `$location.path`). If `$location.path` + * contains redundant trailing slash or is missing one, the route will still match and the + * `$location.path` will be updated to add or drop the trailing slash to exactly match the + * route definition. + * + * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up + * to the next slash are matched and stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain named groups starting with a colon and ending with a star: + * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` + * when the route matches. + * * `path` can contain optional named groups with a question mark: e.g.`:name?`. + * + * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match + * `/color/brown/largecode/code/with/slashes/edit` and extract: + * + * * `color: brown` + * * `largecode: code/with/slashes`. + * + * + * @param {Object} route Mapping information to be assigned to `$route.current` on route + * match. + * + * Object properties: + * + * - `controller` – `{(string|function()=}` – Controller fn that should be associated with + * newly created scope or the name of a {@link angular.Module#controller registered + * controller} if passed as a string. + * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller. + * If present, the controller will be published to scope under the `controllerAs` name. + * - `template` – `{string=|function()=}` – html template as a string or a function that + * returns an html template as a string which should be used by {@link + * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. + * This property takes precedence over `templateUrl`. + * + * If `template` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html + * template that should be used by {@link ngRoute.directive:ngView ngView}. + * + * If `templateUrl` is a function, it will be called with the following parameters: + * + * - `{Array.}` - route parameters extracted from the current + * `$location.path()` by applying the current route + * + * - `resolve` - `{Object.=}` - An optional map of dependencies which should + * be injected into the controller. If any of these dependencies are promises, the router + * will wait for them all to be resolved or one to be rejected before the controller is + * instantiated. + * If all the promises are resolved successfully, the values of the resolved promises are + * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is + * fired. If any of the promises are rejected the + * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. + * For easier access to the resolved dependencies from the template, the `resolve` map will + * be available on the scope of the route, under `$resolve` (by default) or a custom name + * specified by the `resolveAs` property (see below). This can be particularly useful, when + * working with {@link angular.Module#component components} as route templates.
    + *
    + * **Note:** If your scope already contains a property with this name, it will be hidden + * or overwritten. Make sure, you specify an appropriate name for this property, that + * does not collide with other properties on the scope. + *
    + * The map object is: + * + * - `key` – `{string}`: a name of a dependency to be injected into the controller. + * - `factory` - `{string|function}`: If `string` then it is an alias for a service. + * Otherwise if function, then it is {@link auto.$injector#invoke injected} + * and the return value is treated as the dependency. If the result is a promise, it is + * resolved before its value is injected into the controller. Be aware that + * `ngRoute.$routeParams` will still refer to the previous route within these resolve + * functions. Use `$route.current.params` to access the new route parameters, instead. + * + * - `resolveAs` - `{string=}` - The name under which the `resolve` map will be available on + * the scope of the route. If omitted, defaults to `$resolve`. + * + * - `redirectTo` – `{(string|function())=}` – value to update + * {@link ng.$location $location} path with and trigger route redirection. + * + * If `redirectTo` is a function, it will be called with the following parameters: + * + * - `{Object.}` - route parameters extracted from the current + * `$location.path()` by applying the current route templateUrl. + * - `{string}` - current `$location.path()` + * - `{Object}` - current `$location.search()` + * + * The custom `redirectTo` function is expected to return a string which will be used + * to update `$location.path()` and `$location.search()`. + * + * - `[reloadOnSearch=true]` - `{boolean=}` - reload route when only `$location.search()` + * or `$location.hash()` changes. + * + * If the option is set to `false` and url in the browser changes, then + * `$routeUpdate` event is broadcasted on the root scope. + * + * - `[caseInsensitiveMatch=false]` - `{boolean=}` - match routes without being case sensitive + * + * If the option is set to `true`, then the particular route can be matched without being + * case sensitive + * + * @returns {Object} self + * + * @description + * Adds a new route definition to the `$route` service. + */ + this.when = function(path, route) { + //copy original route object to preserve params inherited from proto chain + var routeCopy = shallowCopy(route); + if (angular.isUndefined(routeCopy.reloadOnSearch)) { + routeCopy.reloadOnSearch = true; + } + if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) { + routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch; + } + routes[path] = angular.extend( + routeCopy, + path && pathRegExp(path, routeCopy) + ); + + // create redirection for trailing slashes + if (path) { + var redirectPath = (path[path.length - 1] == '/') + ? path.substr(0, path.length - 1) + : path + '/'; + + routes[redirectPath] = angular.extend( + {redirectTo: path}, + pathRegExp(redirectPath, routeCopy) + ); + } + + return this; + }; + + /** + * @ngdoc property + * @name $routeProvider#caseInsensitiveMatch + * @description + * + * A boolean property indicating if routes defined + * using this provider should be matched using a case insensitive + * algorithm. Defaults to `false`. + */ + this.caseInsensitiveMatch = false; + + /** + * @param path {string} path + * @param opts {Object} options + * @return {?Object} + * + * @description + * Normalizes the given path, returning a regular expression + * and the original path. + * + * Inspired by pathRexp in visionmedia/express/lib/utils.js. + */ + function pathRegExp(path, opts) { + var insensitive = opts.caseInsensitiveMatch, + ret = { + originalPath: path, + regexp: path + }, + keys = ret.keys = []; + + path = path + .replace(/([().])/g, '\\$1') + .replace(/(\/)?:(\w+)(\*\?|[\?\*])?/g, function(_, slash, key, option) { + var optional = (option === '?' || option === '*?') ? '?' : null; + var star = (option === '*' || option === '*?') ? '*' : null; + keys.push({ name: key, optional: !!optional }); + slash = slash || ''; + return '' + + (optional ? '' : slash) + + '(?:' + + (optional ? slash : '') + + (star && '(.+?)' || '([^/]+)') + + (optional || '') + + ')' + + (optional || ''); + }) + .replace(/([\/$\*])/g, '\\$1'); + + ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); + return ret; + } + + /** + * @ngdoc method + * @name $routeProvider#otherwise + * + * @description + * Sets route definition that will be used on route change when no other route definition + * is matched. + * + * @param {Object|string} params Mapping information to be assigned to `$route.current`. + * If called with a string, the value maps to `redirectTo`. + * @returns {Object} self + */ + this.otherwise = function(params) { + if (typeof params === 'string') { + params = {redirectTo: params}; + } + this.when(null, params); + return this; + }; + + + this.$get = ['$rootScope', + '$location', + '$routeParams', + '$q', + '$injector', + '$templateRequest', + '$sce', + function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) { + + /** + * @ngdoc service + * @name $route + * @requires $location + * @requires $routeParams + * + * @property {Object} current Reference to the current route definition. + * The route definition contains: + * + * - `controller`: The controller constructor as defined in the route definition. + * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for + * controller instantiation. The `locals` contain + * the resolved values of the `resolve` map. Additionally the `locals` also contain: + * + * - `$scope` - The current route scope. + * - `$template` - The current route template HTML. + * + * The `locals` will be assigned to the route scope's `$resolve` property. You can override + * the property name, using `resolveAs` in the route definition. See + * {@link ngRoute.$routeProvider $routeProvider} for more info. + * + * @property {Object} routes Object with all route configuration Objects as its properties. + * + * @description + * `$route` is used for deep-linking URLs to controllers and views (HTML partials). + * It watches `$location.url()` and tries to map the path to an existing route definition. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. + * + * The `$route` service is typically used in conjunction with the + * {@link ngRoute.directive:ngView `ngView`} directive and the + * {@link ngRoute.$routeParams `$routeParams`} service. + * + * @example + * This example shows how changing the URL hash causes the `$route` to match a route against the + * URL, and the `ngView` pulls in the partial. + * + * + * + *
    + * Choose: + * Moby | + * Moby: Ch1 | + * Gatsby | + * Gatsby: Ch4 | + * Scarlet Letter
    + * + *
    + * + *
    + * + *
    $location.path() = {{$location.path()}}
    + *
    $route.current.templateUrl = {{$route.current.templateUrl}}
    + *
    $route.current.params = {{$route.current.params}}
    + *
    $route.current.scope.name = {{$route.current.scope.name}}
    + *
    $routeParams = {{$routeParams}}
    + *
    + *
    + * + * + * controller: {{name}}
    + * Book Id: {{params.bookId}}
    + *
    + * + * + * controller: {{name}}
    + * Book Id: {{params.bookId}}
    + * Chapter Id: {{params.chapterId}} + *
    + * + * + * angular.module('ngRouteExample', ['ngRoute']) + * + * .controller('MainController', function($scope, $route, $routeParams, $location) { + * $scope.$route = $route; + * $scope.$location = $location; + * $scope.$routeParams = $routeParams; + * }) + * + * .controller('BookController', function($scope, $routeParams) { + * $scope.name = "BookController"; + * $scope.params = $routeParams; + * }) + * + * .controller('ChapterController', function($scope, $routeParams) { + * $scope.name = "ChapterController"; + * $scope.params = $routeParams; + * }) + * + * .config(function($routeProvider, $locationProvider) { + * $routeProvider + * .when('/Book/:bookId', { + * templateUrl: 'book.html', + * controller: 'BookController', + * resolve: { + * // I will cause a 1 second delay + * delay: function($q, $timeout) { + * var delay = $q.defer(); + * $timeout(delay.resolve, 1000); + * return delay.promise; + * } + * } + * }) + * .when('/Book/:bookId/ch/:chapterId', { + * templateUrl: 'chapter.html', + * controller: 'ChapterController' + * }); + * + * // configure html5 to get links working on jsfiddle + * $locationProvider.html5Mode(true); + * }); + * + * + * + * + * it('should load and compile correct template', function() { + * element(by.linkText('Moby: Ch1')).click(); + * var content = element(by.css('[ng-view]')).getText(); + * expect(content).toMatch(/controller\: ChapterController/); + * expect(content).toMatch(/Book Id\: Moby/); + * expect(content).toMatch(/Chapter Id\: 1/); + * + * element(by.partialLinkText('Scarlet')).click(); + * + * content = element(by.css('[ng-view]')).getText(); + * expect(content).toMatch(/controller\: BookController/); + * expect(content).toMatch(/Book Id\: Scarlet/); + * }); + * + *
    + */ + + /** + * @ngdoc event + * @name $route#$routeChangeStart + * @eventType broadcast on root scope + * @description + * Broadcasted before a route change. At this point the route services starts + * resolving all of the dependencies needed for the route change to occur. + * Typically this involves fetching the view template as well as any dependencies + * defined in `resolve` route property. Once all of the dependencies are resolved + * `$routeChangeSuccess` is fired. + * + * The route change (and the `$location` change that triggered it) can be prevented + * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} + * for more details about event object. + * + * @param {Object} angularEvent Synthetic event object. + * @param {Route} next Future route information. + * @param {Route} current Current route information. + */ + + /** + * @ngdoc event + * @name $route#$routeChangeSuccess + * @eventType broadcast on root scope + * @description + * Broadcasted after a route change has happened successfully. + * The `resolve` dependencies are now available in the `current.locals` property. + * + * {@link ngRoute.directive:ngView ngView} listens for the directive + * to instantiate the controller and render the view. + * + * @param {Object} angularEvent Synthetic event object. + * @param {Route} current Current route information. + * @param {Route|Undefined} previous Previous route information, or undefined if current is + * first route entered. + */ + + /** + * @ngdoc event + * @name $route#$routeChangeError + * @eventType broadcast on root scope + * @description + * Broadcasted if any of the resolve promises are rejected. + * + * @param {Object} angularEvent Synthetic event object + * @param {Route} current Current route information. + * @param {Route} previous Previous route information. + * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. + */ + + /** + * @ngdoc event + * @name $route#$routeUpdate + * @eventType broadcast on root scope + * @description + * The `reloadOnSearch` property has been set to false, and we are reusing the same + * instance of the Controller. + * + * @param {Object} angularEvent Synthetic event object + * @param {Route} current Current/previous route information. + */ + + var forceReload = false, + preparedRoute, + preparedRouteIsUpdateOnly, + $route = { + routes: routes, + + /** + * @ngdoc method + * @name $route#reload + * + * @description + * Causes `$route` service to reload the current route even if + * {@link ng.$location $location} hasn't changed. + * + * As a result of that, {@link ngRoute.directive:ngView ngView} + * creates new scope and reinstantiates the controller. + */ + reload: function() { + forceReload = true; + + var fakeLocationEvent = { + defaultPrevented: false, + preventDefault: function fakePreventDefault() { + this.defaultPrevented = true; + forceReload = false; + } + }; + + $rootScope.$evalAsync(function() { + prepareRoute(fakeLocationEvent); + if (!fakeLocationEvent.defaultPrevented) commitRoute(); + }); + }, + + /** + * @ngdoc method + * @name $route#updateParams + * + * @description + * Causes `$route` service to update the current URL, replacing + * current route parameters with those specified in `newParams`. + * Provided property names that match the route's path segment + * definitions will be interpolated into the location's path, while + * remaining properties will be treated as query params. + * + * @param {!Object} newParams mapping of URL parameter names to values + */ + updateParams: function(newParams) { + if (this.current && this.current.$$route) { + newParams = angular.extend({}, this.current.params, newParams); + $location.path(interpolate(this.current.$$route.originalPath, newParams)); + // interpolate modifies newParams, only query params are left + $location.search(newParams); + } else { + throw $routeMinErr('norout', 'Tried updating route when with no current route'); + } + } + }; + + $rootScope.$on('$locationChangeStart', prepareRoute); + $rootScope.$on('$locationChangeSuccess', commitRoute); + + return $route; + + ///////////////////////////////////////////////////// + + /** + * @param on {string} current url + * @param route {Object} route regexp to match the url against + * @return {?Object} + * + * @description + * Check if the route matches the current url. + * + * Inspired by match in + * visionmedia/express/lib/router/router.js. + */ + function switchRouteMatcher(on, route) { + var keys = route.keys, + params = {}; + + if (!route.regexp) return null; + + var m = route.regexp.exec(on); + if (!m) return null; + + for (var i = 1, len = m.length; i < len; ++i) { + var key = keys[i - 1]; + + var val = m[i]; + + if (key && val) { + params[key.name] = val; + } + } + return params; + } + + function prepareRoute($locationEvent) { + var lastRoute = $route.current; + + preparedRoute = parseRoute(); + preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route + && angular.equals(preparedRoute.pathParams, lastRoute.pathParams) + && !preparedRoute.reloadOnSearch && !forceReload; + + if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) { + if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) { + if ($locationEvent) { + $locationEvent.preventDefault(); + } + } + } + } + + function commitRoute() { + var lastRoute = $route.current; + var nextRoute = preparedRoute; + + if (preparedRouteIsUpdateOnly) { + lastRoute.params = nextRoute.params; + angular.copy(lastRoute.params, $routeParams); + $rootScope.$broadcast('$routeUpdate', lastRoute); + } else if (nextRoute || lastRoute) { + forceReload = false; + $route.current = nextRoute; + if (nextRoute) { + if (nextRoute.redirectTo) { + if (angular.isString(nextRoute.redirectTo)) { + $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params) + .replace(); + } else { + $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search())) + .replace(); + } + } + } + + $q.when(nextRoute). + then(resolveLocals). + then(function(locals) { + // after route change + if (nextRoute == $route.current) { + if (nextRoute) { + nextRoute.locals = locals; + angular.copy(nextRoute.params, $routeParams); + } + $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute); + } + }, function(error) { + if (nextRoute == $route.current) { + $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error); + } + }); + } + } + + function resolveLocals(route) { + if (route) { + var locals = angular.extend({}, route.resolve); + angular.forEach(locals, function(value, key) { + locals[key] = angular.isString(value) ? + $injector.get(value) : + $injector.invoke(value, null, null, key); + }); + var template = getTemplateFor(route); + if (angular.isDefined(template)) { + locals['$template'] = template; + } + return $q.all(locals); + } + } + + + function getTemplateFor(route) { + var template, templateUrl; + if (angular.isDefined(template = route.template)) { + if (angular.isFunction(template)) { + template = template(route.params); + } + } else if (angular.isDefined(templateUrl = route.templateUrl)) { + if (angular.isFunction(templateUrl)) { + templateUrl = templateUrl(route.params); + } + if (angular.isDefined(templateUrl)) { + route.loadedTemplateUrl = $sce.valueOf(templateUrl); + template = $templateRequest(templateUrl); + } + } + return template; + } + + + /** + * @returns {Object} the current active route, by matching it against the URL + */ + function parseRoute() { + // Match a route + var params, match; + angular.forEach(routes, function(route, path) { + if (!match && (params = switchRouteMatcher($location.path(), route))) { + match = inherit(route, { + params: angular.extend({}, $location.search(), params), + pathParams: params}); + match.$$route = route; + } + }); + // No route matched; fallback to "otherwise" route + return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); + } + + /** + * @returns {string} interpolation of the redirect path with the parameters + */ + function interpolate(string, params) { + var result = []; + angular.forEach((string || '').split(':'), function(segment, i) { + if (i === 0) { + result.push(segment); + } else { + var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/); + var key = segmentMatch[1]; + result.push(params[key]); + result.push(segmentMatch[2] || ''); + delete params[key]; + } + }); + return result.join(''); + } + }]; +} + +ngRouteModule.provider('$routeParams', $RouteParamsProvider); + + +/** + * @ngdoc service + * @name $routeParams + * @requires $route + * + * @description + * The `$routeParams` service allows you to retrieve the current set of route parameters. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * The route parameters are a combination of {@link ng.$location `$location`}'s + * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. + * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. + * + * In case of parameter name collision, `path` params take precedence over `search` params. + * + * The service guarantees that the identity of the `$routeParams` object will remain unchanged + * (but its properties will likely change) even when a route change occurs. + * + * Note that the `$routeParams` are only updated *after* a route change completes successfully. + * This means that you cannot rely on `$routeParams` being correct in route resolve functions. + * Instead you can use `$route.current.params` to access the new route's parameters. + * + * @example + * ```js + * // Given: + * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby + * // Route: /Chapter/:chapterId/Section/:sectionId + * // + * // Then + * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} + * ``` + */ +function $RouteParamsProvider() { + this.$get = function() { return {}; }; +} + +ngRouteModule.directive('ngView', ngViewFactory); +ngRouteModule.directive('ngView', ngViewFillContentFactory); + + +/** + * @ngdoc directive + * @name ngView + * @restrict ECA + * + * @description + * # Overview + * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by + * including the rendered template of the current route into the main layout (`index.html`) file. + * Every time the current route changes, the included view changes with it according to the + * configuration of the `$route` service. + * + * Requires the {@link ngRoute `ngRoute`} module to be installed. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM | + * | {@link ng.$animate#leave leave} | when the old element is removed from to the DOM | + * + * The enter and leave animation occur concurrently. + * + * @knownIssue If `ngView` is contained in an asynchronously loaded template (e.g. in another + * directive's templateUrl or in a template loaded using `ngInclude`), then you need to + * make sure that `$route` is instantiated in time to capture the initial + * `$locationChangeStart` event and load the appropriate view. One way to achieve this + * is to have it as a dependency in a `.run` block: + * `myModule.run(['$route', function() {}]);` + * + * @scope + * @priority 400 + * @param {string=} onload Expression to evaluate whenever the view updates. + * + * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll + * $anchorScroll} to scroll the viewport after the view is updated. + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated + * as an expression yields a truthy value. + * @example + + +
    + Choose: + Moby | + Moby: Ch1 | + Gatsby | + Gatsby: Ch4 | + Scarlet Letter
    + +
    +
    +
    +
    + +
    $location.path() = {{main.$location.path()}}
    +
    $route.current.templateUrl = {{main.$route.current.templateUrl}}
    +
    $route.current.params = {{main.$route.current.params}}
    +
    $routeParams = {{main.$routeParams}}
    +
    +
    + + +
    + controller: {{book.name}}
    + Book Id: {{book.params.bookId}}
    +
    +
    + + +
    + controller: {{chapter.name}}
    + Book Id: {{chapter.params.bookId}}
    + Chapter Id: {{chapter.params.chapterId}} +
    +
    + + + .view-animate-container { + position:relative; + height:100px!important; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .view-animate { + padding:10px; + } + + .view-animate.ng-enter, .view-animate.ng-leave { + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; + + display:block; + width:100%; + border-left:1px solid black; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + padding:10px; + } + + .view-animate.ng-enter { + left:100%; + } + .view-animate.ng-enter.ng-enter-active { + left:0; + } + .view-animate.ng-leave.ng-leave-active { + left:-100%; + } + + + + angular.module('ngViewExample', ['ngRoute', 'ngAnimate']) + .config(['$routeProvider', '$locationProvider', + function($routeProvider, $locationProvider) { + $routeProvider + .when('/Book/:bookId', { + templateUrl: 'book.html', + controller: 'BookCtrl', + controllerAs: 'book' + }) + .when('/Book/:bookId/ch/:chapterId', { + templateUrl: 'chapter.html', + controller: 'ChapterCtrl', + controllerAs: 'chapter' + }); + + $locationProvider.html5Mode(true); + }]) + .controller('MainCtrl', ['$route', '$routeParams', '$location', + function($route, $routeParams, $location) { + this.$route = $route; + this.$location = $location; + this.$routeParams = $routeParams; + }]) + .controller('BookCtrl', ['$routeParams', function($routeParams) { + this.name = "BookCtrl"; + this.params = $routeParams; + }]) + .controller('ChapterCtrl', ['$routeParams', function($routeParams) { + this.name = "ChapterCtrl"; + this.params = $routeParams; + }]); + + + + + it('should load and compile correct template', function() { + element(by.linkText('Moby: Ch1')).click(); + var content = element(by.css('[ng-view]')).getText(); + expect(content).toMatch(/controller\: ChapterCtrl/); + expect(content).toMatch(/Book Id\: Moby/); + expect(content).toMatch(/Chapter Id\: 1/); + + element(by.partialLinkText('Scarlet')).click(); + + content = element(by.css('[ng-view]')).getText(); + expect(content).toMatch(/controller\: BookCtrl/); + expect(content).toMatch(/Book Id\: Scarlet/); + }); + +
    + */ + + +/** + * @ngdoc event + * @name ngView#$viewContentLoaded + * @eventType emit on the current ngView scope + * @description + * Emitted every time the ngView content is reloaded. + */ +ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; +function ngViewFactory($route, $anchorScroll, $animate) { + return { + restrict: 'ECA', + terminal: true, + priority: 400, + transclude: 'element', + link: function(scope, $element, attr, ctrl, $transclude) { + var currentScope, + currentElement, + previousLeaveAnimation, + autoScrollExp = attr.autoscroll, + onloadExp = attr.onload || ''; + + scope.$on('$routeChangeSuccess', update); + update(); + + function cleanupLastView() { + if (previousLeaveAnimation) { + $animate.cancel(previousLeaveAnimation); + previousLeaveAnimation = null; + } + + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if (currentElement) { + previousLeaveAnimation = $animate.leave(currentElement); + previousLeaveAnimation.then(function() { + previousLeaveAnimation = null; + }); + currentElement = null; + } + } + + function update() { + var locals = $route.current && $route.current.locals, + template = locals && locals.$template; + + if (angular.isDefined(template)) { + var newScope = scope.$new(); + var current = $route.current; + + // Note: This will also link all children of ng-view that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-view on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function(clone) { + $animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() { + if (angular.isDefined(autoScrollExp) + && (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }); + cleanupLastView(); + }); + + currentElement = clone; + currentScope = current.scope = newScope; + currentScope.$emit('$viewContentLoaded'); + currentScope.$eval(onloadExp); + } else { + cleanupLastView(); + } + } + } + }; +} + +// This directive is called during the $transclude call of the first `ngView` directive. +// It will replace and compile the content of the element with the loaded template. +// We need this directive so that the element content is already filled when +// the link function of another directive on the same element as ngView +// is called. +ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; +function ngViewFillContentFactory($compile, $controller, $route) { + return { + restrict: 'ECA', + priority: -400, + link: function(scope, $element) { + var current = $route.current, + locals = current.locals; + + $element.html(locals.$template); + + var link = $compile($element.contents()); + + if (current.controller) { + locals.$scope = scope; + var controller = $controller(current.controller, locals); + if (current.controllerAs) { + scope[current.controllerAs] = controller; + } + $element.data('$ngControllerController', controller); + $element.children().data('$ngControllerController', controller); + } + scope[current.resolveAs || '$resolve'] = locals; + + link(scope); + } + }; +} + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-route.min.js b/src/main/resources/static/module/angular/angular-route.min.js new file mode 100644 index 0000000..2fa073f --- /dev/null +++ b/src/main/resources/static/module/angular/angular-route.min.js @@ -0,0 +1,16 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(E,d){'use strict';function y(t,l,g){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(b,e,a,c,k){function p(){m&&(g.cancel(m),m=null);h&&(h.$destroy(),h=null);n&&(m=g.leave(n),m.then(function(){m=null}),n=null)}function B(){var a=t.current&&t.current.locals;if(d.isDefined(a&&a.$template)){var a=b.$new(),c=t.current;n=k(a,function(a){g.enter(a,null,n||e).then(function(){!d.isDefined(A)||A&&!b.$eval(A)||l()});p()});h=c.scope=a;h.$emit("$viewContentLoaded"); +h.$eval(s)}else p()}var h,n,m,A=a.autoscroll,s=a.onload||"";b.$on("$routeChangeSuccess",B);B()}}}function w(d,l,g){return{restrict:"ECA",priority:-400,link:function(b,e){var a=g.current,c=a.locals;e.html(c.$template);var k=d(e.contents());if(a.controller){c.$scope=b;var p=l(a.controller,c);a.controllerAs&&(b[a.controllerAs]=p);e.data("$ngControllerController",p);e.children().data("$ngControllerController",p)}b[a.resolveAs||"$resolve"]=c;k(b)}}}var x,C,s=d.module("ngRoute",["ng"]).provider("$route", +function(){function t(b,e){return d.extend(Object.create(b),e)}function l(b,d){var a=d.caseInsensitiveMatch,c={originalPath:b,regexp:b},g=c.keys=[];b=b.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)(\*\?|[\?\*])?/g,function(b,a,d,c){b="?"===c||"*?"===c?"?":null;c="*"===c||"*?"===c?"*":null;g.push({name:d,optional:!!b});a=a||"";return""+(b?"":a)+"(?:"+(b?a:"")+(c&&"(.+?)"||"([^/]+)")+(b||"")+")"+(b||"")}).replace(/([\/$\*])/g,"\\$1");c.regexp=new RegExp("^"+b+"$",a?"i":"");return c}x=d.isArray;C= +d.isObject;var g={};this.when=function(b,e){var a;a=void 0;if(x(e)){a=a||[];for(var c=0,k=e.length;c + * + * See {@link ngSanitize.$sanitize `$sanitize`} for usage. + */ + +/** + * @ngdoc service + * @name $sanitize + * @kind function + * + * @description + * Sanitizes an html string by stripping all potentially dangerous tokens. + * + * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are + * then serialized back to properly escaped html string. This means that no unsafe input can make + * it into the returned string. + * + * The whitelist for URL sanitization of attribute values is configured using the functions + * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider + * `$compileProvider`}. + * + * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}. + * + * @param {string} html HTML input. + * @returns {string} Sanitized HTML. + * + * @example + + + +
    + Snippet: + + + + + + + + + + + + + + + + + + + + + + + + + +
    DirectiveHowSourceRendered
    ng-bind-htmlAutomatically uses $sanitize
    <div ng-bind-html="snippet">
    </div>
    ng-bind-htmlBypass $sanitize by explicitly trusting the dangerous value +
    <div ng-bind-html="deliberatelyTrustDangerousSnippet()">
    +</div>
    +
    ng-bindAutomatically escapes
    <div ng-bind="snippet">
    </div>
    +
    +
    + + it('should sanitize the html snippet by default', function() { + expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). + toBe('

    an html\nclick here\nsnippet

    '); + }); + + it('should inline raw snippet if bound to a trusted value', function() { + expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). + toBe("

    an html\n" + + "click here\n" + + "snippet

    "); + }); + + it('should escape snippet without any filter', function() { + expect(element(by.css('#bind-default div')).getInnerHtml()). + toBe("<p style=\"color:blue\">an html\n" + + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + + "snippet</p>"); + }); + + it('should update', function() { + element(by.model('snippet')).clear(); + element(by.model('snippet')).sendKeys('new text'); + expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). + toBe('new text'); + expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( + 'new text'); + expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( + "new <b onclick=\"alert(1)\">text</b>"); + }); +
    +
    + */ + + +/** + * @ngdoc provider + * @name $sanitizeProvider + * + * @description + * Creates and configures {@link $sanitize} instance. + */ +function $SanitizeProvider() { + var svgEnabled = false; + + this.$get = ['$$sanitizeUri', function($$sanitizeUri) { + if (svgEnabled) { + extend(validElements, svgElements); + } + return function(html) { + var buf = []; + htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { + return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); + })); + return buf.join(''); + }; + }]; + + + /** + * @ngdoc method + * @name $sanitizeProvider#enableSvg + * @kind function + * + * @description + * Enables a subset of svg to be supported by the sanitizer. + * + *
    + *

    By enabling this setting without taking other precautions, you might expose your + * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned + * outside of the containing element and be rendered over other elements on the page (e.g. a login + * link). Such behavior can then result in phishing incidents.

    + * + *

    To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg + * tags within the sanitized content:

    + * + *
    + * + *
    
    +   *   .rootOfTheIncludedContent svg {
    +   *     overflow: hidden !important;
    +   *   }
    +   *   
    + *
    + * + * @param {boolean=} flag Enable or disable SVG support in the sanitizer. + * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called + * without an argument or self for chaining otherwise. + */ + this.enableSvg = function(enableSvg) { + if (isDefined(enableSvg)) { + svgEnabled = enableSvg; + return this; + } else { + return svgEnabled; + } + }; + + ////////////////////////////////////////////////////////////////////////////////////////////////// + // Private stuff + ////////////////////////////////////////////////////////////////////////////////////////////////// + + bind = angular.bind; + extend = angular.extend; + forEach = angular.forEach; + isDefined = angular.isDefined; + lowercase = angular.lowercase; + noop = angular.noop; + + htmlParser = htmlParserImpl; + htmlSanitizeWriter = htmlSanitizeWriterImpl; + + // Regular Expressions for parsing tags and attributes + var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, + // Match everything outside of normal chars and " (quote character) + NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g; + + + // Good source of info about elements and attributes + // http://dev.w3.org/html5/spec/Overview.html#semantics + // http://simon.html5.org/html-elements + + // Safe Void Elements - HTML5 + // http://dev.w3.org/html5/spec/Overview.html#void-elements + var voidElements = toMap("area,br,col,hr,img,wbr"); + + // Elements that you can, intentionally, leave open (and which close themselves) + // http://dev.w3.org/html5/spec/Overview.html#optional-tags + var optionalEndTagBlockElements = toMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), + optionalEndTagInlineElements = toMap("rp,rt"), + optionalEndTagElements = extend({}, + optionalEndTagInlineElements, + optionalEndTagBlockElements); + + // Safe Block Elements - HTML5 + var blockElements = extend({}, optionalEndTagBlockElements, toMap("address,article," + + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul")); + + // Inline Elements - HTML5 + var inlineElements = extend({}, optionalEndTagInlineElements, toMap("a,abbr,acronym,b," + + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); + + // SVG Elements + // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements + // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. + // They can potentially allow for arbitrary javascript to be executed. See #11290 + var svgElements = toMap("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph," + + "hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline," + + "radialGradient,rect,stop,svg,switch,text,title,tspan"); + + // Blocked Elements (will be stripped) + var blockedElements = toMap("script,style"); + + var validElements = extend({}, + voidElements, + blockElements, + inlineElements, + optionalEndTagElements); + + //Attributes that have href and hence need to be sanitized + var uriAttrs = toMap("background,cite,href,longdesc,src,xlink:href"); + + var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + + 'valign,value,vspace,width'); + + // SVG attributes (without "id" and "name" attributes) + // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes + var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + + 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + + 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + + 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + + 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + + 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + + 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + + 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + + 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + + 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + + 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + + 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + + 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + + 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + + 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); + + var validAttrs = extend({}, + uriAttrs, + svgAttrs, + htmlAttrs); + + function toMap(str, lowercaseKeys) { + var obj = {}, items = str.split(','), i; + for (i = 0; i < items.length; i++) { + obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; + } + return obj; + } + + var inertBodyElement; + (function(window) { + var doc; + if (window.document && window.document.implementation) { + doc = window.document.implementation.createHTMLDocument("inert"); + } else { + throw $sanitizeMinErr('noinert', "Can't create an inert html document"); + } + var docElement = doc.documentElement || doc.getDocumentElement(); + var bodyElements = docElement.getElementsByTagName('body'); + + // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one + if (bodyElements.length === 1) { + inertBodyElement = bodyElements[0]; + } else { + var html = doc.createElement('html'); + inertBodyElement = doc.createElement('body'); + html.appendChild(inertBodyElement); + doc.appendChild(html); + } + })(window); + + /** + * @example + * htmlParser(htmlString, { + * start: function(tag, attrs) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * }); + * + * @param {string} html string + * @param {object} handler + */ + function htmlParserImpl(html, handler) { + if (html === null || html === undefined) { + html = ''; + } else if (typeof html !== 'string') { + html = '' + html; + } + inertBodyElement.innerHTML = html; + + //mXSS protection + var mXSSAttempts = 5; + do { + if (mXSSAttempts === 0) { + throw $sanitizeMinErr('uinput', "Failed to sanitize html because the input is unstable"); + } + mXSSAttempts--; + + // strip custom-namespaced attributes on IE<=11 + if (window.document.documentMode) { + stripCustomNsAttrs(inertBodyElement); + } + html = inertBodyElement.innerHTML; //trigger mXSS + inertBodyElement.innerHTML = html; + } while (html !== inertBodyElement.innerHTML); + + var node = inertBodyElement.firstChild; + while (node) { + switch (node.nodeType) { + case 1: // ELEMENT_NODE + handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); + break; + case 3: // TEXT NODE + handler.chars(node.textContent); + break; + } + + var nextNode; + if (!(nextNode = node.firstChild)) { + if (node.nodeType == 1) { + handler.end(node.nodeName.toLowerCase()); + } + nextNode = node.nextSibling; + if (!nextNode) { + while (nextNode == null) { + node = node.parentNode; + if (node === inertBodyElement) break; + nextNode = node.nextSibling; + if (node.nodeType == 1) { + handler.end(node.nodeName.toLowerCase()); + } + } + } + } + node = nextNode; + } + + while (node = inertBodyElement.firstChild) { + inertBodyElement.removeChild(node); + } + } + + function attrToMap(attrs) { + var map = {}; + for (var i = 0, ii = attrs.length; i < ii; i++) { + var attr = attrs[i]; + map[attr.name] = attr.value; + } + return map; + } + + + /** + * Escapes all potentially dangerous characters, so that the + * resulting string can be safely inserted into attribute or + * element text. + * @param value + * @returns {string} escaped text + */ + function encodeEntities(value) { + return value. + replace(/&/g, '&'). + replace(SURROGATE_PAIR_REGEXP, function(value) { + var hi = value.charCodeAt(0); + var low = value.charCodeAt(1); + return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; + }). + replace(NON_ALPHANUMERIC_REGEXP, function(value) { + return '&#' + value.charCodeAt(0) + ';'; + }). + replace(//g, '>'); + } + + /** + * create an HTML/XML writer which writes to buffer + * @param {Array} buf use buf.join('') to get out sanitized html string + * @returns {object} in the form of { + * start: function(tag, attrs) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * } + */ + function htmlSanitizeWriterImpl(buf, uriValidator) { + var ignoreCurrentElement = false; + var out = bind(buf, buf.push); + return { + start: function(tag, attrs) { + tag = lowercase(tag); + if (!ignoreCurrentElement && blockedElements[tag]) { + ignoreCurrentElement = tag; + } + if (!ignoreCurrentElement && validElements[tag] === true) { + out('<'); + out(tag); + forEach(attrs, function(value, key) { + var lkey = lowercase(key); + var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); + if (validAttrs[lkey] === true && + (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { + out(' '); + out(key); + out('="'); + out(encodeEntities(value)); + out('"'); + } + }); + out('>'); + } + }, + end: function(tag) { + tag = lowercase(tag); + if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { + out(''); + } + if (tag == ignoreCurrentElement) { + ignoreCurrentElement = false; + } + }, + chars: function(chars) { + if (!ignoreCurrentElement) { + out(encodeEntities(chars)); + } + } + }; + } + + + /** + * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare + * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want + * to allow any of these custom attributes. This method strips them all. + * + * @param node Root element to process + */ + function stripCustomNsAttrs(node) { + if (node.nodeType === window.Node.ELEMENT_NODE) { + var attrs = node.attributes; + for (var i = 0, l = attrs.length; i < l; i++) { + var attrNode = attrs[i]; + var attrName = attrNode.name.toLowerCase(); + if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) { + node.removeAttributeNode(attrNode); + i--; + l--; + } + } + } + + var nextNode = node.firstChild; + if (nextNode) { + stripCustomNsAttrs(nextNode); + } + + nextNode = node.nextSibling; + if (nextNode) { + stripCustomNsAttrs(nextNode); + } + } +} + +function sanitizeText(chars) { + var buf = []; + var writer = htmlSanitizeWriter(buf, noop); + writer.chars(chars); + return buf.join(''); +} + + +// define ngSanitize module and register $sanitize service +angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); + +/** + * @ngdoc filter + * @name linky + * @kind function + * + * @description + * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and + * plain email address links. + * + * Requires the {@link ngSanitize `ngSanitize`} module to be installed. + * + * @param {string} text Input text. + * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in. + * @param {object|function(url)} [attributes] Add custom attributes to the link element. + * + * Can be one of: + * + * - `object`: A map of attributes + * - `function`: Takes the url as a parameter and returns a map of attributes + * + * If the map of attributes contains a value for `target`, it overrides the value of + * the target parameter. + * + * + * @returns {string} Html-linkified and {@link $sanitize sanitized} text. + * + * @usage + + * + * @example + + +
    + Snippet: + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FilterSourceRendered
    linky filter +
    <div ng-bind-html="snippet | linky">
    </div>
    +
    +
    +
    linky target +
    <div ng-bind-html="snippetWithSingleURL | linky:'_blank'">
    </div>
    +
    +
    +
    linky custom attributes +
    <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}">
    </div>
    +
    +
    +
    no filter
    <div ng-bind="snippet">
    </div>
    + + + angular.module('linkyExample', ['ngSanitize']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.snippet = + 'Pretty text with some links:\n'+ + 'http://angularjs.org/,\n'+ + 'mailto:us@somewhere.org,\n'+ + 'another@somewhere.org,\n'+ + 'and one more: ftp://127.0.0.1/.'; + $scope.snippetWithSingleURL = 'http://angularjs.org/'; + }]); + + + it('should linkify the snippet with urls', function() { + expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). + toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); + expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); + }); + + it('should not linkify snippet without the linky filter', function() { + expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). + toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); + expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); + }); + + it('should update', function() { + element(by.model('snippet')).clear(); + element(by.model('snippet')).sendKeys('new http://link.'); + expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). + toBe('new http://link.'); + expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); + expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) + .toBe('new http://link.'); + }); + + it('should work with the target property', function() { + expect(element(by.id('linky-target')). + element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()). + toBe('http://angularjs.org/'); + expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); + }); + + it('should optionally add custom attributes', function() { + expect(element(by.id('linky-custom-attributes')). + element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()). + toBe('http://angularjs.org/'); + expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow'); + }); + + + */ +angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { + var LINKY_URL_REGEXP = + /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, + MAILTO_REGEXP = /^mailto:/i; + + var linkyMinErr = angular.$$minErr('linky'); + var isDefined = angular.isDefined; + var isFunction = angular.isFunction; + var isObject = angular.isObject; + var isString = angular.isString; + + return function(text, target, attributes) { + if (text == null || text === '') return text; + if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text); + + var attributesFn = + isFunction(attributes) ? attributes : + isObject(attributes) ? function getAttributesObject() {return attributes;} : + function getEmptyAttributesObject() {return {};}; + + var match; + var raw = text; + var html = []; + var url; + var i; + while ((match = raw.match(LINKY_URL_REGEXP))) { + // We can not end in these as they are sometimes found at the end of the sentence + url = match[0]; + // if we did not match ftp/http/www/mailto then assume mailto + if (!match[2] && !match[4]) { + url = (match[3] ? 'http://' : 'mailto:') + url; + } + i = match.index; + addText(raw.substr(0, i)); + addLink(url, match[0].replace(MAILTO_REGEXP, '')); + raw = raw.substring(i + match[0].length); + } + addText(raw); + return $sanitize(html.join('')); + + function addText(text) { + if (!text) { + return; + } + html.push(sanitizeText(text)); + } + + function addLink(url, text) { + var key, linkAttributes = attributesFn(url); + html.push(''); + addText(text); + html.push(''); + } + }; +}]); + + +})(window, window.angular); diff --git a/src/main/resources/static/module/angular/angular-sanitize.min.js b/src/main/resources/static/module/angular/angular-sanitize.min.js new file mode 100644 index 0000000..ca82fd2 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-sanitize.min.js @@ -0,0 +1,16 @@ +/* + AngularJS v1.5.8 + (c) 2010-2016 Google, Inc. http://angularjs.org + License: MIT +*/ +(function(s,g){'use strict';function H(g){var l=[];t(l,A).chars(g);return l.join("")}var B=g.$$minErr("$sanitize"),C,l,D,E,q,A,F,t;g.module("ngSanitize",[]).provider("$sanitize",function(){function k(a,e){var b={},c=a.split(","),h;for(h=0;h/g,">")}function u(a){if(a.nodeType===s.Node.ELEMENT_NODE)for(var e=a.attributes,b=0,c=e.length;b"))},end:function(a){a= +q(a);b||!0!==w[a]||!0===y[a]||(c(""));a==b&&(b=!1)},chars:function(a){b||c(G(a))}}};var J=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,K=/([^\#-~ |!])/g,y=k("area,br,col,hr,img,wbr"),d=k("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),r=k("rp,rt"),p=l({},r,d),d=l({},d,k("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul")),r=l({},r,k("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")), +x=k("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,stop,svg,switch,text,title,tspan"),z=k("script,style"),w=l({},y,d,r,p),n=k("background,cite,href,longdesc,src,xlink:href"),p=k("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,valign,value,vspace,width"), +r=k("accent-height,accumulate,additive,alphabetic,arabic-form,ascent,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan", +!0),m=l({},n,r,p),f;(function(a){if(a.document&&a.document.implementation)a=a.document.implementation.createHTMLDocument("inert");else throw B("noinert");var e=(a.documentElement||a.getDocumentElement()).getElementsByTagName("body");1===e.length?f=e[0]:(e=a.createElement("html"),f=a.createElement("body"),e.appendChild(f),a.appendChild(e))})(s)});g.module("ngSanitize").filter("linky",["$sanitize",function(k){var l=/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, +q=/^mailto:/i,u=g.$$minErr("linky"),v=g.isDefined,s=g.isFunction,t=g.isObject,y=g.isString;return function(d,g,p){function x(a){a&&m.push(H(a))}function z(a,b){var c,d=w(a);m.push("');x(b);m.push("")}if(null==d||""===d)return d;if(!y(d))throw u("notstring",d);for(var w=s(p)?p:t(p)?function(){return p}:function(){return{}},n=d,m=[],f,a;d=n.match(l);)f=d[0],d[2]|| +d[4]||(f=(d[3]?"http://":"mailto:")+f),a=d.index,x(n.substr(0,a)),z(f,d[0].replace(q,"")),n=n.substring(a+d[0].length);x(n);return k(m.join(""))}}])})(window,window.angular); +//# sourceMappingURL=angular-sanitize.min.js.map diff --git a/src/main/resources/static/module/angular/angular-sanitize.min.js.map b/src/main/resources/static/module/angular/angular-sanitize.min.js.map new file mode 100644 index 0000000..8d2a1a9 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-sanitize.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-sanitize.min.js", +"lineCount":15, +"mappings":"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", +"sources":["angular-sanitize.js"], +"names":["window","angular","sanitizeText","chars","buf","htmlSanitizeWriter","writer","noop","join","$sanitizeMinErr","$$minErr","bind","extend","forEach","isDefined","lowercase","htmlParser","module","provider","$SanitizeProvider","toMap","str","lowercaseKeys","obj","items","split","i","length","attrToMap","attrs","map","ii","attr","name","value","encodeEntities","replace","SURROGATE_PAIR_REGEXP","hi","charCodeAt","low","NON_ALPHANUMERIC_REGEXP","stripCustomNsAttrs","node","nodeType","Node","ELEMENT_NODE","attributes","l","attrNode","attrName","toLowerCase","lastIndexOf","removeAttributeNode","nextNode","firstChild","nextSibling","svgEnabled","$get","$$sanitizeUri","validElements","svgElements","html","uri","isImage","test","enableSvg","this.enableSvg","htmlParserImpl","handler","undefined","inertBodyElement","innerHTML","mXSSAttempts","document","documentMode","start","nodeName","textContent","end","parentNode","removeChild","htmlSanitizeWriterImpl","uriValidator","ignoreCurrentElement","out","push","tag","blockedElements","key","lkey","validAttrs","uriAttrs","voidElements","optionalEndTagBlockElements","optionalEndTagInlineElements","optionalEndTagElements","blockElements","inlineElements","htmlAttrs","svgAttrs","implementation","doc","createHTMLDocument","bodyElements","getElementsByTagName","documentElement","getDocumentElement","createElement","appendChild","filter","$sanitize","LINKY_URL_REGEXP","MAILTO_REGEXP","linkyMinErr","isFunction","isObject","isString","text","target","addText","addLink","url","linkAttributes","attributesFn","getAttributesObject","getEmptyAttributesObject","raw","match","index","substr","substring"] +} diff --git a/src/main/resources/static/module/angular/angular-scenario.js b/src/main/resources/static/module/angular/angular-scenario.js new file mode 100644 index 0000000..834f3d3 --- /dev/null +++ b/src/main/resources/static/module/angular/angular-scenario.js @@ -0,0 +1,44134 @@ +/*eslint-disable no-unused-vars*/ +/*! + * jQuery JavaScript Library v3.1.0 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2016-07-07T21:44Z + */ +( function( global, factory ) { + +if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. + +var arr = []; + +var document = window.document; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + + + + function DOMEval( code, doc ) { + doc = doc || document; + + var script = doc.createElement( "script" ); + + script.text = code; + doc.head.appendChild( script ).parentNode.removeChild( script ); + } +/* global Symbol */ +// Defining this global in .eslintrc would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.1.0", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android <=4.0 only + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + + // As of jQuery 3.0, isNumeric is limited to + // strings and numbers (primitives or objects) + // that can be coerced to finite numbers (gh-2662) + var type = jQuery.type( obj ); + return ( type === "number" || type === "string" ) && + + // parseFloat NaNs numeric-cast false positives ("") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + !isNaN( obj - parseFloat( obj ) ); + }, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + DOMEval( code ); + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE <=9 - 11, Edge 12 - 13 + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // Support: Android <=4.0 only + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.0 + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-01-04 + */ +(function( window ) {'use strict'; + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[i] = "#" + nid + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement("fieldset"); + + try { + return !!fn( el ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + // Known :disabled false positives: + // IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset) + // not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Check form elements and option elements for explicit disabling + return "label" in elem && elem.disabled === disabled || + "form" in elem && elem.disabled === disabled || + + // Check non-disabled form elements for fieldset[disabled] ancestors + "form" in elem && elem.disabled === false && ( + // Support: IE6-11+ + // Ancestry is covered for us + elem.isDisabled === disabled || + + // Otherwise, assume any non-