# 云手机示例

使用开放 API 进行云手机管理的完整工作示例。

**基本网址**：`https://api.morelogin.com`

## 完整工作流程：身份验证→创建→安装应用程序→ADB

### curl

```bash
# 1. Get access token
TOKEN=$(curl -s -X POST https://api.morelogin.com/oauth2/token \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "YOUR_API_ID",
    "client_secret": "YOUR_API_KEY",
    "grant_type": "client_credentials"
  }' | jq -r '.data.access_token')

echo "Token: $TOKEN"

# 2. Create a cloud phone
curl -X POST https://api.morelogin.com/cloudphone/create \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "name": "my-cloud-phone",
    "areaId": 1,
    "groupId": "your-group-id"
  }'

# 3. Start the cloud phone
curl -X POST https://api.morelogin.com/cloudphone/start \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"ids": ["CLOUD_PHONE_ID"]}'

# 4. Install an app
curl -X POST https://api.morelogin.com/cloudphone/app/install \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "id": CLOUD_PHONE_ID,
    "packageName": "com.example.app",
    "versionCode": 1
  }'
```

### Python（请求）

```python
import requests

BASE = "https://api.morelogin.com"
API_ID = "YOUR_API_ID"
API_KEY = "YOUR_API_KEY"

# 1. Get access token
resp = requests.post(f"{BASE}/oauth2/token", json={
    "client_id": API_ID,
    "client_secret": API_KEY,
    "grant_type": "client_credentials"
})
token = resp.json()["data"]["access_token"]
headers = {"Authorization": f"Bearer {token}"}
print(f"Token acquired (expires in {resp.json()['data']['expires_in']}s)")

# 2. Create a cloud phone
resp = requests.post(f"{BASE}/cloudphone/create", headers=headers, json={
    "name": "automation-phone",
    "areaId": 1,
    "groupId": "your-group-id"
})
phone_id = resp.json()["data"]["id"]
print(f"Created cloud phone: {phone_id}")

# 3. Start the cloud phone
resp = requests.post(f"{BASE}/cloudphone/start", headers=headers, json={
    "ids": [str(phone_id)]
})
print(f"Start result: {resp.json()['code']}")

# 4. Install app
resp = requests.post(f"{BASE}/cloudphone/app/install", headers=headers, json={
    "id": phone_id,
    "packageName": "com.example.app",
    "versionCode": 1
})
print(f"App install: {resp.json()['code']}")

# 5. Enable ADB
resp = requests.post(f"{BASE}/cloudphone/enableAdb", headers=headers, json={
    "id": phone_id
})
adb_info = resp.json()["data"]
print(f"ADB enabled - connect with: adb connect {adb_info.get('host')}:{adb_info.get('port')}")

# 6. Stop cloud phone when done
resp = requests.post(f"{BASE}/cloudphone/stop", headers=headers, json={
    "ids": [str(phone_id)]
})
print("Cloud phone stopped.")
```

### Node.js（axios）

```javascript
const axios = require('axios');

const BASE = 'https://api.morelogin.com';
const API_ID = 'YOUR_API_ID';
const API_KEY = 'YOUR_API_KEY';

async function main() {
  // 1. Get access token
  const authResp = await axios.post(`${BASE}/oauth2/token`, {
    client_id: API_ID,
    client_secret: API_KEY,
    grant_type: 'client_credentials'
  });
  const token = authResp.data.data.access_token;
  const headers = { Authorization: `Bearer ${token}` };
  console.log('Token acquired');

  // 2. Create a cloud phone
  const createResp = await axios.post(`${BASE}/cloudphone/create`,
    { name: 'automation-phone', areaId: 1 },
    { headers }
  );
  const phoneId = createResp.data.data.id;
  console.log(`Created cloud phone: ${phoneId}`);

  // 3. Start cloud phone
  await axios.post(`${BASE}/cloudphone/start`,
    { ids: [String(phoneId)] },
    { headers }
  );
  console.log('Cloud phone started');

  // 4. Install app
  await axios.post(`${BASE}/cloudphone/app/install`,
    { id: phoneId, packageName: 'com.example.app', versionCode: 1 },
    { headers }
  );
  console.log('App installation initiated');

  // 5. Enable ADB
  const adbResp = await axios.post(`${BASE}/cloudphone/enableAdb`,
    { id: phoneId },
    { headers }
  );
  console.log('ADB enabled:', adbResp.data.data);

  // 6. Stop when done
  await axios.post(`${BASE}/cloudphone/stop`,
    { ids: [String(phoneId)] },
    { headers }
  );
  console.log('Cloud phone stopped');
}

main().catch(console.error);
```

## 文件上传示例（Python）

```python
import requests

BASE = "https://api.morelogin.com"
headers = {"Authorization": "Bearer YOUR_TOKEN"}

phone_id = 1234567890

# 1. Get presigned upload URL
resp = requests.post(f"{BASE}/cloudphone/uploadUrl", headers=headers, json={
    "id": phone_id,
    "fileName": "config.json"
})
upload_url = resp.json()["data"]["presignedUrl"]

# 2. Upload file to presigned URL
with open("config.json", "rb") as f:
    requests.put(upload_url, data=f)

# 3. Trigger file upload to cloud phone
resp = requests.post(f"{BASE}/cloudphone/uploadFile", headers=headers, json={
    "id": str(phone_id),
    "url": upload_url,
    "uploadDest": "/Download"
})
file_id = resp.json()["data"]["fileId"]

# 4. Check upload result
resp = requests.post(f"{BASE}/cloudphone/uploadFileResult", headers=headers, json={
    "id": str(phone_id),
    "fileId": file_id
})
print(f"Upload status: {resp.json()['data']['status']}")  # 1 = success
```