[Service] Add a service app to register device to devicehome.net 78/265978/10 accepted/tizen/unified/20211115.141638 submit/tizen/20211112.160020
authorYoungsoo Choi <kenshin.choi@samsung.com>
Wed, 3 Nov 2021 05:08:47 +0000 (22:08 -0700)
committerYoungsoo Choi <kenshin.choi@samsung.com>
Fri, 12 Nov 2021 00:56:46 +0000 (16:56 -0800)
DeviceHome is running on demand on TV profile to save idle time memory usage.
The Initializer service app registers device to devicehome.net once,
before launching the DeviceHome.

The service app will be called by wrt-service-broker
only if device IP, device name, and login ID have been changed.

Change-Id: I9edb3bef2fa20070408cd71a47c3eec6e03836e2
Signed-off-by: Youngsoo Choi <kenshin.choi@samsung.com>
device_home/service/initializer/service.js [new file with mode: 0755]
device_home/service/service.js
packaging/config_tv.xml.in

diff --git a/device_home/service/initializer/service.js b/device_home/service/initializer/service.js
new file mode 100755 (executable)
index 0000000..1d782a0
--- /dev/null
@@ -0,0 +1,111 @@
+const TAG = '[Initializer]';
+const https = require('https');
+const is_tv = webapis.cachedProperty !== undefined;
+
+class Initializer {
+  constructor() {
+    this.DEVICE_HOME = 'devicehome.net';
+    this.blacklist = [
+      '1',
+      '10.0.2.15', // emulator
+      '127.0.0.1', // localhost
+      '192.168.250.250' // sdb
+    ];
+    this.device_ip = this.getIp();
+    this.device_name = webapis.mde.getDeviceName();
+    this.login_id = webapis.mde.getCurrentLoginId();
+  }
+
+  registerDevice() {
+    return new Promise(resolve => {
+      if (this.device_ip === false) {
+        console.log(`${TAG} failed to get device_ip`);
+        return;
+      }
+      const device = {
+        device_ip: this.device_ip,
+        device_name: this.device_name,
+        login_id: this.login_id
+      };
+      console.log(`${TAG} device :`, device);
+      const data = JSON.stringify(device);
+      const request_options = {
+        headers: {
+          'Content-Type': 'application/json',
+          'Content-Length': data.length
+        },
+        hostname: this.DEVICE_HOME,
+        method: 'POST',
+        path: '/registerDevice',
+        port: 443,
+        rejectUnauthorized: false
+      };
+      const req = https.request(request_options, res => {
+        console.log(`${TAG} status : ${res.statusCode}`);
+        res.setEncoding('utf8');
+        res.on('data', response => {
+          console.log(`${TAG} response: ${response}`);
+          if (response === 'DONE' || response === 'DEVICE_EXISTS') {
+            this.saveFile();
+          }
+          resolve(true);
+        });
+      });
+      req.on('error', error => {
+        console.log(`${TAG} error: ${error}`);
+        resolve(false);
+      });
+      req.write(data);
+      req.end();
+    });
+  }
+
+  saveFile() {
+    const device = `${this.device_ip}:${this.device_name}:${this.login_id}`;
+    const file_handler_write = tizen.filesystem.openFile('wgt-private/device_home.txt', 'rwo');
+    file_handler_write.writeString(device);
+    const file_handler_read = tizen.filesystem.openFile('wgt-private/device_home.txt', 'r');
+    const contents = file_handler_read.readString();
+    console.log(`${TAG} saved : ${contents}`);
+    file_handler_write.close();
+    file_handler_read.close();
+  }
+
+  getIp() {
+    const interfaces = require('os').networkInterfaces();
+    for (const device in interfaces) {
+      if (interfaces.hasOwnProperty(device)) {
+        const iface = interfaces[device];
+        for (let i = 0; i < iface.length; i++) {
+          const alias = iface[i];
+          console.log(`${TAG} found : ${alias.address}`);
+          if (alias.family === 'IPv4' && !alias.internal &&
+              !this.blacklist.includes(alias.address)) {
+            return alias.address;
+          }
+        }
+      }
+    }
+    return false;
+  }
+}
+
+module.exports.onStart = async function() {
+  console.log(`${TAG} onStart is called`);
+  if (!is_tv || typeof webapis.mde === 'undefined') {
+    console.log(`${TAG} failed to register device`);
+    tizen.application.getCurrentApplication().exit();
+    return;
+  }
+  const initializer = new Initializer();
+  await initializer.registerDevice();
+  tizen.application.getCurrentApplication().exit();
+};
+
+module.exports.onStop = function() {
+  console.log(`${TAG} onStop is called`);
+};
+
+module.exports.onRequest = function() {
+  console.log(`${TAG} onRequest is called`);
+};
index 8660d972ca8f1f479643f3a09aabf6b694d0da75..289fd629bb9a20227576b52cd7daab2b838865ea 100755 (executable)
@@ -20,13 +20,12 @@ const sessionMiddleware = session({
     secure: false,
 }});
 
-const PUBLIC_DOMAIN = 'http://devicehome.net';
+const PUBLIC_DOMAIN = 'https://devicehome.net';
 const TAG = '[DeviceHome][service.js]'
 const TIZEN_WEB_APP_SHARED_RESOURCES = 'shared/res/';
 const WEBCLIP_DIRECTORY = 'webclip';
 const WEBCLIP_MANIFEST = 'manifest.json';
 const is_tv = webapis.cachedProperty !== undefined;
-const emulator_ip = '10.0.2.15';
 const local_ip = '127.0.0.1';
 const non_ip_list = [
   '1',
@@ -254,47 +253,6 @@ function getWebClipsList() {
   return result;
 }
 
-function sendLoginIdAndDeviceName(login_id, device_ip) {
-  let device_name = 'Tizen';
-  if (typeof webapis.mde !== 'undefined')
-    device_name = webapis.mde.getDeviceName();
-  console.log(`${TAG} login_id : ${login_id}`);
-  console.log(`${TAG} device_ip : ${device_ip}`);
-  console.log(`${TAG} device_name : ${device_name}`);
-
-  const xhr = new XMLHttpRequest();
-  const keyVal = {
-    login_id: login_id,
-    device_name: device_name,
-    device_ip: device_ip
-  };
-  xhr.onreadystatechange = function() {
-    if (xhr.readyState === xhr.DONE) {
-      console.log(`${TAG} xhr text: ${xhr.responseText}`);
-      if (xhr.status === 200 || xhr.status === 201) {
-        if (xhr.responseText === 'DEVICE_EXISTS') {
-          console.log(`${TAG} device exists`);
-        }
-      } else {
-        console.log(`${TAG} xhr error: ${xhr.status}`);
-      }
-    }
-  }
-  xhr.open('POST', PUBLIC_DOMAIN + '/registerDevice');
-  xhr.setRequestHeader('Content-Type', 'application/json');
-  xhr.send(JSON.stringify(keyVal));
-}
-
-function updateDNSresolver(device_ip) {
-  console.log(`${TAG} Server is listening on ${device_ip}:${g.port}`);
-  if (is_tv && typeof webapis.mde !== 'undefined') {
-    const login_id = webapis.mde.getCurrentLoginId();
-    sendLoginIdAndDeviceName(login_id, device_ip);
-  } else {
-    console.log(`${TAG} Samsung account isn't available`);
-  }
-}
-
 function comparePincode(req, res, encrypted) {
   console.log(`${TAG} comparePincode`);
   console.log(`${TAG} encrypted : ${encrypted}`);
@@ -568,19 +526,7 @@ var HTTPserverStart = function() {
 
   httpserver = http.createServer(app);
   httpserver.listen(g.port, function() {
-    const interfaces = require('os').networkInterfaces();
-    for (const devName in interfaces) {
-      if (interfaces.hasOwnProperty(devName)) {
-        const iface = interfaces[devName];
-        for (let i = 0; i < iface.length; i++) {
-          const alias = iface[i];
-          if (alias.family === 'IPv4' && !non_ip_list.includes(alias.address) &&
-              !alias.internal && alias.address !== emulator_ip) {
-            updateDNSresolver(alias.address);
-          }
-        }
-      }
-    }
+    console.log(`Device home is running on port ${g.port}`);
   });
   relayServer(httpserver, dataApps, sessionMiddleware, clientPublicKeys);
 };
@@ -618,5 +564,4 @@ module.exports.onStop = function() {
 };
 
 module.exports.onRequest = function() {
-}
-
+};
index 3e59715ecb862946e7820c004c7d85a3fd52efa6..cf869c3eacf32e5c663f581326c145f7abdfc432 100644 (file)
@@ -19,4 +19,9 @@
         <tizen:description>DeviceHomeService</tizen:description>
         <tizen:metadata key="http://samsung.com/tv/metadata/use.drm" value="false"/>
     </tizen:service>
+    <tizen:service id="9z6IujVul3.DeviceHomeInitializer" type="global">
+        <tizen:content src="service/initializer/service.js"/>
+        <tizen:name>DeviceHomeInitializer</tizen:name>
+        <tizen:description>DeviceHomeInitializer</tizen:description>
+    </tizen:service>
 </widget>