프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / DTI_PID / License.py @ ea6b6336

이력 | 보기 | 이력해설 | 다운로드 (6.38 KB)

1
# coding: utf-8
2
"""
3
    This is license module
4
"""
5

    
6
import sys
7
import os
8

    
9
from PyQt5.QtCore import *
10
from PyQt5.QtGui import *
11
from PyQt5.QtWidgets import *
12
from PyQt5.QtSvg import *
13
from PyQt5.QtCore import QTranslator
14
from PyQt5.QtCore import QLocale
15
import base64
16

    
17
import License_UI
18

    
19

    
20
class QLicenseDialog(QDialog):
21
    """ This is License dialog class """
22

    
23
    KEY = 'Image Drawing to Intelligent Drawing'
24

    
25
    def __init__(self, parent):
26
        QDialog.__init__(self, parent)
27

    
28
        self.ui = License_UI.Ui_DialogLicense()
29
        self.ui.setupUi(self)
30
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
31
        self.setFixedSize(self.size())
32

    
33
    @property
34
    def license(self):
35
        """ return license key setted by user """
36
        return self.ui.lineEditLicense.text()
37

    
38
    @staticmethod
39
    def process_running():
40
        """ check if program is running inside samsung engineering """
41
        import subprocess
42
        import socket
43
        import ipaddress
44

    
45
        n = 0  # number of instances of the program running
46
        CREATE_NO_WINDOW = 0x08000000
47
        prog = [line.split() for line in
48
                subprocess.check_output("tasklist", creationflags=CREATE_NO_WINDOW).splitlines()]
49
        [prog.pop(e) for e in [0, 1, 2]]  # useless
50
        for task in prog:
51
            if (task[0].upper() == 'EPTRAY.EXE') or (task[0].upper() == 'ICTRAY.EXE') or (
52
                    task[0].upper() == 'ICTRAY64.EXE'):
53
                n = n + 1
54

    
55
        if n >= 2:
56
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
57
            s.connect(("8.8.8.8", 80))
58
            ip = s.getsockname()[0]
59
            if ipaddress.ip_address(ip) in ipaddress.ip_network('66.85.31.0/255'):
60
                return True
61

    
62
        return False
63

    
64
    @staticmethod
65
    def check_license_key():
66
        """ check license key with computer name """
67
        from AppDocData import AppDocData
68
        from datetime import datetime, timedelta
69

    
70
        try:
71
            if QLicenseDialog.process_running(): return True
72

    
73
            appDocData = AppDocData.instance()
74
            configs = appDocData.getAppConfigs('app', 'license')
75
            configs2 = appDocData.getAppConfigs('app', 'expiration')
76
            if configs and 1 == len(configs):
77
                if 'DOFTECH' in configs[0].value:
78
                    configs[0].value = configs[0].value.replace('DOFTECH', '')
79
                decoded = QLicenseDialog.decode(QLicenseDialog.KEY, configs[0].value)
80
                if decoded.upper() == os.environ['COMPUTERNAME'].upper():
81
                    if configs2 and 1 == len(configs2):
82
                        decoded2 = QLicenseDialog.decode(QLicenseDialog.KEY, configs2[0].value).split('-')
83
                        ex_date = datetime(int(decoded2[0]), int(decoded2[1]), int(decoded2[2]), int(decoded2[3]), int(decoded2[4]), int(decoded2[5]))
84
                        if ex_date > datetime.now():
85
                            return True
86
                        else:
87
                            QMessageBox.information(None, 'Information', 'Trial version has expired.')
88
                            return False
89
                    else:
90
                        return True
91
                    
92
            '''
93
            configs = appDocData.getAppConfigs('app', 'license')
94
            if configs and 1 == len(configs):
95
                decoded = QLicenseDialog.decode(QLicenseDialog.KEY, configs[0].value)
96
                if decoded.upper() == os.environ['COMPUTERNAME'].upper(): return True
97
            '''
98

    
99
            dialog = QLicenseDialog(None)
100
            dialog.exec_()
101
            if dialog.isAccepted: return True
102
        except Exception as ex:
103
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
104
                                                          sys.exc_info()[-1].tb_lineno)
105
            print(message)
106

    
107
        return False
108

    
109
    @staticmethod
110
    def encode(key, clear):
111
        enc = []
112
        for i in range(len(clear)):
113
            key_c = key[i % len(key)]
114
            enc_c = (ord(clear[i]) + ord(key_c)) % 256
115
            enc.append(enc_c)
116
        return base64.urlsafe_b64encode(bytes(enc))
117

    
118
    @staticmethod
119
    def decode(key, enc):
120
        dec = []
121
        try:
122
            enc = base64.urlsafe_b64decode(enc)
123
            for i in range(len(enc)):
124
                key_c = key[i % len(key)]
125
                dec_c = chr((256 + enc[i] - ord(key_c)) % 256)
126
                dec.append(dec_c)
127
        except Exception as ex:
128
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
129
                                                      sys.exc_info()[-1].tb_lineno))
130

    
131
        return "".join(dec)
132

    
133
    def accept(self):
134
        from AppDocData import AppDocData
135
        from AppDocData import Config
136

    
137
        try:
138
            _translate = QCoreApplication.translate
139
            origin_text = self.license
140
            decoded = QLicenseDialog.decode(QLicenseDialog.KEY, self.license.replace('DOFTECH', ''))
141
            if decoded.upper() == os.environ['COMPUTERNAME'].upper():
142
                appDocData = AppDocData.instance()
143

    
144
                # save license key
145
                configs = []
146
                configs.append(Config('app', 'license', origin_text))
147
                appDocData.saveAppConfigs(configs)
148
                # up to here
149

    
150
                self.isAccepted = True
151
                QDialog.accept(self)
152
            else:
153
                msg = QMessageBox()
154
                msg.setIcon(QMessageBox.Critical)
155
                msg.setText(self.tr(
156
                    'Invalid license key.\n(Expected Computer Name({}) is not match to your computer name({}))').format(
157
                    'decoded', os.environ['COMPUTERNAME']))
158
                msg.setWindowTitle(_translate('License', "License"))
159
                msg.setStandardButtons(QMessageBox.Ok)
160
                msg.exec_()
161
        except Exception as ex:
162
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
163
                                                          sys.exc_info()[-1].tb_lineno)
164
            print(message)
165

    
166
    def reject(self):
167
        self.isAccepted = False
168
        QDialog.reject(self)
169

    
170

    
171
if __name__ == '__main__':
172
    from License import QLicenseDialog
173

    
174
    var = input('Enter Computer Name: ')
175
    license = QLicenseDialog.encode(QLicenseDialog.KEY, var)
176
    print(license)
클립보드 이미지 추가 (최대 크기: 500 MB)