File size: 4,229 Bytes
fbf957b
8896972
 
 
 
 
 
 
 
fbf957b
 
 
 
8896972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf957b
 
 
 
 
 
 
 
 
8896972
fbf957b
 
8896972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf957b
8896972
fbf957b
 
 
 
0ef3fee
fbf957b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8896972
0ef3fee
 
 
fbf957b
0ef3fee
8896972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { HfApi } = require('@huggingface/hub');

class HFDatasetManager {
  constructor() {
    this.hfToken = process.env.HF_TOKEN;
    this.datasetId = process.env.HF_DATASET_ID || "Detomo/houzou-devices";
    this.fileName = "devices.json";
    this.isEnabled = !!this.hfToken;
    
    if (this.isEnabled) {
      this.hfApi = new HfApi({ accessToken: this.hfToken });
    }
    
    console.log(`πŸ€— HF Dataset Manager initialized`);
    console.log(`   Dataset: ${this.datasetId}`);
    console.log(`   Enabled: ${this.isEnabled}`);
  }

  async loadDevices() {
    if (!this.isEnabled) {
      console.log('⚠️ HF Dataset disabled - no token provided');
      return new Map();
    }

    try {
      console.log('πŸ“₯ Loading devices from HF dataset...');
      
      const fileUrl = `https://huggingface.co/datasets/${this.datasetId}/resolve/main/${this.fileName}`;
      const response = await fetch(fileUrl, {
        headers: {
          'Authorization': `Bearer ${this.hfToken}`
        }
      });

      if (response.status === 404) {
        console.log('πŸ“ No devices file found in dataset, creating new one');
        await this.saveDevices(new Map());
        return new Map();
      }

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      const deviceMap = new Map(data);
      
      console.log(`πŸ“₯ Loaded ${deviceMap.size} devices from HF dataset`);
      return deviceMap;
      
    } catch (error) {
      console.error('❌ Error loading devices from HF dataset:', error);
      console.log('⚠️ Falling back to empty device list');
      return new Map();
    }
  }

  async saveDevices(deviceMap) {
    if (!this.isEnabled) {
      console.log('⚠️ HF Dataset disabled - cannot save devices');
      return false;
    }

    try {
      console.log(`πŸ’Ύ Saving ${deviceMap.size} devices to HF dataset...`);
      
      const devicesArray = Array.from(deviceMap.entries());
      const jsonData = JSON.stringify(devicesArray, null, 2);
      
      // Create a buffer from the JSON data
      const fileContent = Buffer.from(jsonData, 'utf8');
      
      // Upload using HfApi.uploadFile
      await this.hfApi.uploadFile({
        repo: this.datasetId,
        file: {
          path: this.fileName,
          content: fileContent
        },
        repoType: 'dataset',
        commitMessage: `Update devices data (${deviceMap.size} devices)`
      });
      
      console.log(`βœ… Successfully saved ${deviceMap.size} devices to HF dataset`);
      return true;
      
    } catch (error) {
      console.error('❌ Error saving devices to HF dataset:', error);
      return false;
    }
  }

  async createDatasetIfNotExists() {
    if (!this.isEnabled) {
      console.log('⚠️ HF Dataset disabled - cannot create dataset');
      return false;
    }

    try {
      console.log('πŸ” Checking if dataset exists...');
      
      // Try to check if dataset exists
      try {
        await this.hfApi.repoInfo({ repo: this.datasetId, repoType: 'dataset' });
        console.log('βœ… Dataset already exists');
        return true;
      } catch (error) {
        if (error.message.includes('404')) {
          console.log('πŸ“ Dataset not found, creating new one...');
          
          // Create new dataset
          await this.hfApi.createRepo({
            repo: this.datasetId,
            repoType: 'dataset',
            description: 'Device tokens for Houzou Medical App notifications'
          });
          
          console.log('βœ… Dataset created successfully');
          
          // Create initial empty devices file
          await this.saveDevices(new Map());
          return true;
        }
        throw error;
      }
      
    } catch (error) {
      console.error('❌ Error initializing dataset:', error);
      console.log('⚠️ Dataset initialization failed, will use fallback');
      return false;
    }
  }

  isReady() {
    return this.isEnabled;
  }

  getStatus() {
    return {
      enabled: this.isEnabled,
      datasetId: this.datasetId,
      hasToken: !!this.hfToken
    };
  }
}

module.exports = HFDatasetManager;