Spaces:
Sleeping

File size: 6,425 Bytes
995c7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import fs from "fs";
import path from "path";
import { execSync } from "child_process";

// 1. Read config to get token and space target
const CONFIG_PATH = path.join(process.cwd(), "data", "config.json");
if (!fs.existsSync(CONFIG_PATH)) {
  console.error("Config file not found at", CONFIG_PATH);
  process.exit(1);
}

const config = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8"));
const token = config.hfToken;
const space = config.hfSpace;

if (!token || !space) {
  console.error("Hugging Face space path or token is missing from config.json!");
  console.error("Current settings: Space:", space, "Token:", token ? "FOUND" : "MISSING");
  process.exit(1);
}

const tempDir = path.join(process.cwd(), "data", `hf_project_push_${Date.now()}`);
console.log(`[Hugging Face Setup] Space path: ${space}`);
console.log(`[Hugging Face Setup] Creating temporary workspace at: ${tempDir}`);

// Ensure tempDir is clean
if (fs.existsSync(tempDir)) {
  fs.rmSync(tempDir, { recursive: true, force: true });
}
fs.mkdirSync(tempDir, { recursive: true });

try {
  // Cloning space
  console.log("[Hugging Face Setup] Cloning Space repository...");
  const gitUrl = `https://user:${token}@huggingface.co/spaces/${space}`;
  execSync(`git clone ${gitUrl} ${tempDir} --depth 1`, {
    env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
    stdio: "inherit"
  });

  console.log("[Hugging Face Setup] Cloned successfully. Moving files...");

  // Write .dockerignore and Dockerfile and README.md
  const readmeContent = `---
title: Streamapi
emoji: 📺
colorFrom: blue
colorTo: indigo
sdk: docker
pinned: false
---

# Live Stream M3U8 Extractor

This application is hosted on Hugging Face Spaces!
It automatically crawls live channels to retrieve M3U8 streaming sources and compiles them into a cached playlist.
`;

  const dockerfileContent = `FROM node:20-slim

WORKDIR /app

# Install git
RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*

# Copy package config files
COPY package*.json ./

# Install all dependencies (production & development for compilation)
RUN npm install

# Copy full source
COPY . .

# Build application (generates /dist and /dist/server.cjs)
RUN npm run build

# Configure default directory permissions
RUN mkdir -p /app/data && chmod -R 777 /app/data

# Expose Space port
EXPOSE 7860
ENV PORT=7860
ENV NODE_ENV=production

# Start container
CMD ["npm", "run", "start"]
`;

  const dockerignoreContent = `node_modules
dist
.git
.github
*.log
data/hf_project_push_*
data/hf_push_*
`;

  // Custom function to copy directory recursively while ignoring certain folders
  function copyRecursiveSync(src: string, dest: string, ignorePatterns: RegExp[]) {
    const stats = fs.statSync(src);
    const isDir = stats.isDirectory();

    const isIgnored = ignorePatterns.some(pat => pat.test(src) || pat.test(path.basename(src)));
    if (isIgnored) return;

    if (isDir) {
      if (!fs.existsSync(dest)) {
        fs.mkdirSync(dest, { recursive: true });
      }
      fs.readdirSync(src).forEach((child) => {
        copyRecursiveSync(path.join(src, child), path.join(dest, child), ignorePatterns);
      });
    } else {
      fs.copyFileSync(src, dest);
    }
  }

  // Clear everything in clone directory except .git
  fs.readdirSync(tempDir).forEach(file => {
    if (file !== ".git") {
      const fullPath = path.join(tempDir, file);
      fs.rmSync(fullPath, { recursive: true, force: true });
    }
  });

  const rootFilesToCopy = fs.readdirSync(process.cwd());
  const ignoreList = [
    /node_modules/,
    /dist/,
    /\.git$/,
    /\.github/,
    /hf_project_push_/,
    /hf_push_/,
    /\.env/,
    /package-lock\.json/
  ];

  console.log("[Hugging Face Setup] Copying project files...");
  rootFilesToCopy.forEach((file) => {
    if (file !== "data" && file !== "node_modules" && file !== "dist" && file !== ".git") {
      copyRecursiveSync(path.join(process.cwd(), file), path.join(tempDir, file), ignoreList);
    }
  });

  // Make sure we copy the critical parts of data folder (channels/configs) but NOT other temp stuff
  if (fs.existsSync(path.join(process.cwd(), "data"))) {
    fs.mkdirSync(path.join(tempDir, "data"), { recursive: true });
    fs.readdirSync(path.join(process.cwd(), "data")).forEach(dataFile => {
      if (dataFile === "config.json") {
        const fullLocalPath = path.join(process.cwd(), "data", dataFile);
        const configData = JSON.parse(fs.readFileSync(fullLocalPath, "utf-8"));
        // Strip out the hfToken to comply with HF security checks, but leave the other parts intact
        configData.hfToken = "";
        fs.writeFileSync(path.join(tempDir, "data", dataFile), JSON.stringify(configData, null, 2), "utf-8");
      }
    });
  }

  // Write HF config files directly
  console.log("[Hugging Face Setup] Injecting Dockerfile, dockerignore & README.md metadata...");
  fs.writeFileSync(path.join(tempDir, "README.md"), readmeContent, "utf-8");
  fs.writeFileSync(path.join(tempDir, "Dockerfile"), dockerfileContent, "utf-8");
  fs.writeFileSync(path.join(tempDir, ".dockerignore"), dockerignoreContent, "utf-8");

  // Git configure, commit, and push
  const gitCmd = (cmd: string) => {
    console.log(`[Git] Executing: ${cmd}`);
    return execSync(cmd, {
      cwd: tempDir,
      encoding: "utf8",
      env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }
    });
  };

  gitCmd("git config user.name 'M3U8 Auto Stream Deployer'");
  gitCmd("git config user.email 'deployer@streamapi.com'");
  gitCmd("git add .");
  
  const status = gitCmd("git status --porcelain").trim();
  if (status.length === 0) {
    console.log("[Hugging Face Setup] No file changes to push. Project is fully up-to-date inside Hugging Face Space repo!");
  } else {
    gitCmd("git commit -m 'Deploy full project code with Docker runtime'");
    console.log("[Hugging Face Setup] Pushing files directly to main branch on Hugging Face...");
    gitCmd("git push origin main");
    console.log("[Hugging Face Setup] Push succeeded! App will build and launch on your Hugging Face space.");
  }
} catch (error: any) {
  console.error("[Hugging Face Setup] An error occurred during setup & push:", error.message || error);
} finally {
  // Always clean up temp directory
  if (fs.existsSync(tempDir)) {
    console.log("[Hugging Face Setup] Cleaning up temporary workspace...");
    fs.rmSync(tempDir, { recursive: true, force: true });
  }
}