Completed
Push — master ( a05ad4...48a210 )
by Sepand
01:17
created

wait_func()   A

Complexity

Conditions 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
c 1
b 1
f 0
dl 0
loc 4
rs 10
1
import os
2
import shutil  # Library For Work With File In High Level Like Copy
3
import datetime  # For Adding System Time To Homepage
4
import webbrowser
5
from params import *
6
import socket
7
import requests
8
import re
9
import time
10
meta_input=""
11
12
def create_folder():  # This Function Create Empty Folder At Begin
13
    folder_flag = 0
14
    list_of_folders = os.listdir(work_dir)
15
    if "doc" not in list_of_folders:
16
        os.mkdir("doc")
17
        file = open(os.path.join(doc_dir, "index.txt"), "w")
18
        file.write("This is For First Page . . .")
19
        file.close()
20
        folder_flag += 1
21
    if "image" not in list_of_folders:
22
        os.mkdir("image")
23
        folder_flag += 1
24
    if "output" not in list_of_folders:
25
        os.mkdir("output")
26
        folder_flag += 1
27
    if "font" not in list_of_folders:
28
        os.mkdir("font")
29
        folder_flag += 1
30
    if folder_flag > 0:
31
        return True
32
    else:
33
        return False
34
35
36
def page_name_update():  # This Function Update Page Names
37
    for i in os.listdir(doc_dir):
38
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
39
            actual_name.append(i[:-4])
40
            page_name.append(i[:-4])
41
42
43
def menu_maker():  # Top Menu Maker In each html page
44
    result = "<center>"
45
    for i in range(len(page_name)):
46
        if page_name[i] == "Home":
47
            targets_blank = ""
48
        else:
49
            targets_blank = 'target="blank"'
50
        result = result + '\t<a href="' + actual_name[i] + '.html"' + targets_blank + '>' + page_name[
51
            i] + "</a>\n"  # Hyper Link To Each Page In HTML File
52
        result += "&nbsp\n"
53
    result += "</center>"
54
    result = result + "\t\t" + break_line  # Add Break line to End Of The Menu
55
    return result  # Return All Of The Menu
56
57
58
def menu_writer():  # Write menu_maker output in html file
59
    message = menu_maker()
60
    for i in range(len(page_name)):
61
        file = open(os.path.join(out_dir, actual_name[i] + ".html"), "a")
62
        file.write(message)
63
        file.close()
64
65
66
def print_meta():
67
    global meta_input
68
    meta_input = input("Please Enter Your Name : ")
69
    static_meta = '<meta name="description" content="Welcome to homepage of ' + meta_input + '"/>\n'
70
    static_meta=static_meta+'<meta property="og:title" content="'+meta_input+'"/>\n'
71
    static_meta=static_meta+'<meta property="og:site_name" content="'+meta_input+'"/>\n'
72
    static_meta=static_meta+'<meta property="og:image" content="favicon.ico" />\n'
73
    if len(meta_input) < 4:
74
        warnings.append("[Warning] Your input for name is too short!!")
75
    return static_meta
76
77
78
def html_init(name):  # Create Initial Form Of each Html Page Like Title And HTML  And Body Tag
79
    html_name = os.path.join(out_dir, name + ".html")
80
    file = open(html_name, "w")
81
    file.write("<html>\n")
82
    file.write("\t<head>\n")
83
    if name == "index":
84
        file.write("\t\t<title>Welcome To My Homepage</title>\n")
85
    else:
86
        file.write("\t\t<title>" + name.upper() + "</title>\n")
87
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
88
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
89
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
90
91
    if name == 'index':  # Add meta only for index page
92
        file.write(print_meta())
93
94
    file.write("\t</head>\n")
95
    file.write('\t<body class="body_tag">\n')
96
    file.close()
97
98
99
def html_end(name):  # Create End Of The Html file
100
    html_name = os.path.join(out_dir, name + ".html")
101
    file = open(html_name, "a")
102
    file.write("\t</body>\n")
103
    file.write("</html>")
104
    file.close()
105
106
107
def close_files():
108
    for i in files:
109
        i.close()
110
111
def LSM_translate(line,center):
112
    line.strip()
113
    text = line
114
    header_start = '<h4 class="color_tag">'
115
    header_end = "</h4>"
116
    if line.find("[L]") != -1:
117
        header_start = '<h2 class="color_tag">'
118
        header_end = "</h2>"
119
        text = line[3:]
120
    elif line.find("[S]") != -1:
121
        header_start = '<h5 class="color_tag">'
122
        header_end = "</h5>"
123
        text = line[3:]
124
    elif line.find("[M]") != -1:
125
        text = line[3:]
126
    if center:  # Centerizes Text If Condition Is True For Manual Centering
127
        header_start = "<center>" + header_start
128
        header_end += "</center>"
129
    if text.find("[center]") != -1:  # Find Center Tag In Each Line
130
        header_start = "<center>" + header_start
131
        header_end += "</center>"
132
        text = text[:text.find("[center]")]
133
    return [text,header_end,header_start]
134
135
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
136
    text_code=""
137
    for line in text_file:
138
        if len(line)==1:
139
            text_code = space
140
        else:
141
            text_header=LSM_translate(line,center)
142
            text=text_header[0]
143
            header_end =text_header[1]
144
            header_start =text_header[2]
145
            text_code = header_start + text + header_end + "\n"
146
        file.write(text_code)
147
    if close:
148
        file.close()
149
150
151
def print_image(file, close=False, imformat="jpg"):  # Write Image Part OF The Page
152
    for i in range(len(size_box)):
153
        print(i, "-", size_box[i])
154
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
155
    image_size_string = size_box[2]  # Getting Html String From size_box list default mode (Medium)
156
    if 0 <= image_size < len(size_box):
157
        image_size_string = size_box[image_size]
158
    image_code = '<center><img src="image.' + imformat + '"' + ', width=' + image_size_string + '></img></center>\n'
159
    file.write(image_code)
160
    if close:
161
        file.close()
162
163
164
def print_download(file, name, link, center=False, close=False):  # Create Download Link In Page
165
    link_code = "<a href=" + '"' + link + '"' + target_blank + '>' + name + "</a>"
166
    if center:
167
        link_code = "<center>" + link_code + "</center>"
168
    file.write(link_code + "\n")
169
    file.write(break_line)
170
    if close:
171
        file.close()
172
173
174
def print_adv(file, close=True):
175
    file.write(break_line)
176
    file.write(
177
        '<center><a href=' + '"' + homepage + '"' + target_blank + '>' + "Generated " + today_time + " By" + "QPage " + version + "</a> </center>")
178
    if close:
179
        file.close()
180
181
182
def contain(name):  # main function That Open Each Page HTML File and call other function to write data in it
183
    file = open(os.path.join(out_dir, name + ".html"), "a")
184
    text_file = open(os.path.join(doc_dir, name + ".txt"), "r")
185
    files.append(file)
186
    files.append(text_file)
187
    resume_name = ""
188
    image_name = ""
189
    imformat = "jpg"
190
    if name == "index":
191
        file_of_images = os.listdir(image_dir)
192
        for i in range(len(file_of_images)):
193
            for form in imformat_box:
194
                if file_of_images[i].find("." + form) != -1:
195
                    image_name = os.path.join(image_dir, file_of_images[i])
196
                    imformat = form
197
                    global image_counter
198
                    image_counter=1
199
                    break
200
        shutil.copyfile(image_name, os.path.join(out_dir, "image." + imformat))
201
        print_image(file, imformat=imformat)
202
        print_text(text_file, file)
203
        print_adv(file)
204
    elif name == "Resume":
205
        file_of_docs = os.listdir(doc_dir)
206
        for i in range(len(file_of_docs)):
207
            if file_of_docs[i].find(".pdf") != -1:
208
                resume_name = os.path.join(doc_dir, file_of_docs[i])
209
                break
210
        shutil.copyfile(resume_name, os.path.join(out_dir, "Resume.pdf"))
211
        print_download(file, "Download Full Version", "Resume.pdf", center=True)
212
        print_text(text_file, file)
213
        # print_adv(file)
214
    else:
215
        print_text(text_file, file)
216
        # print_adv(file)
217
218
219
def clear_folder(path):  # This Function Get Path Of Foldr And Delte Its Contains
220
    if os.path.exists(path):
221
        list_of_files = os.listdir(path)
222
        for file in list_of_files:
223
            os.remove(os.path.join(path, file))
224
    else:
225
        os.mkdir(path)
226
227
228
def print_warning():
229
    print(str(len(warnings)) + " Warning , 0 Error")
230
    for i in range(len(warnings)):
231
        print(str(i + 1) + "-" + warnings[i])
232
233
def css_init():
234
    for i in range(len(color_box)):
235
        print(i, "-", color_box[i])
236
    back_color_code = int(input("Please enter your background color : "))
237
    if back_color_code not in range(7):
238
        back_color_code = 0
239
    text_color_code = int(input("Please enter your text color : "))
240
    if text_color_code not in range(7):
241
        text_color_code = 1
242
    if text_color_code == back_color_code:
243
        warnings.append("[Warning] Your text color and background color are same!!")
244
    background_color = color_box[back_color_code]  # convert code to color string in color_box
245
    text_color = color_box[text_color_code]  # convert code to color string in color_box
246
    return [background_color,text_color]
247
248
def css_creator():  # Ask For background and text color in
249
    font_flag = 0  # 0 If there is no font file in font_folder
250
    font_section = 'font-family : Georgia , serif;\n'
251
    colors=css_init()
252
    background_color=colors[0]
253
    text_color=colors[1]
254
    font_folder = os.listdir(font_dir)
255
    for i in font_folder:
256
        for j in range(len(font_format)):  # search for other font format in font box
257
            if i.lower().find(font_format[j]) != -1:  # If there is a font in font folder
258
                shutil.copyfile(os.path.join(font_dir, i),
259
                                os.path.join(out_dir, "qpage" + font_format[j]))  # copy font file to output folder
260
                font_flag = 1  # Turn Flag On
261
                current_font_format = font_format[j]  # font format of current selected font for css editing
262
    css_file = open(os.path.join(out_dir, "styles.css"), "w")  # open css file
263
    if font_flag == 1:  # check flag if it is 1
264
        css_file.write(
265
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage" + current_font_format + ");\n}\n")  # wrtie font-face in html
266
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
267
        for i in range(len(fontstyle_box)):
268
            print(i, "-", fontstyle_box[i])
269
        font_style = int(input(" Please choose your font style "))
270
        if font_style < len(fontstyle_box):
271
            font_style = fontstyle_box[font_style]
272
        else:
273
            font_style = "normal"
274
        font_section = font_section + "font-style:" + font_style + ";\n"
275
    css_file.write(
276
        ".body_tag{\n" + "background-color:" + background_color + ";\n" + font_section + css_margin +css_animation_1+ "}\n")  # write body tag
277
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
278
    css_file.write(css_animation_2)
279
    css_file.close()  # close css file
280
281
282
def preview():
283
    webbrowser.open(os.path.join(out_dir, "index.html"))
284
285
286
def error_finder():
287
    error_vector = []
288
    pass_vector = []
289
    pdf_counter = 0
290
    if image_counter == 1:
291
        pass_vector.append("[Pass] Your profile image in OK!!")
292
    else:
293
        error_vector.append("[Error] Your profile image is not in correct format")
294
    if len(doc_list) == 0:
295
        error_vector.append("[Error] There is no file in doc folder ( index.txt and .pdf file in necessary)")
296
    else:
297
        if "index.txt" in doc_list:
298
            pass_vector.append("[Pass] index.txt file OK!")
299
        else:
300
            error_vector.append("[Error] index.txt is not in doc folder!")
301
        for j in doc_list:
302
            if j.find(".pdf") != -1:
303
                pdf_counter = 1
304
                break
305
        if pdf_counter == 0:
306
            error_vector.append("[Error] Where Is Your Resume File? It should be in doc folder")
307
        else:
308
            pass_vector.append("[Pass] Your Resume File is OK!!")
309
    return [error_vector, pass_vector]
310
311
312
def icon_creator():
313
    icon_flag=0
314
    for file in os.listdir(image_dir):
315
        if file.endswith('ico'):
316
            shutil.copy(os.path.join(image_dir, file), out_dir)
317
            os.rename(os.path.join(out_dir, file), os.path.join(out_dir, 'favicon.ico'))
318
            icon_flag=1
319
            break
320
    if "favicon.ico" in os.listdir(work_dir) and icon_flag==0:
321
        shutil.copy(os.path.join(work_dir, "favicon.ico"), out_dir)
322
        warnings.append("[warning] There is no icon for this website")
323
def robot_maker(): # This Function Create Robots.txt for pages
324
    robots=open(os.path.join(out_dir,"robots.txt"),"w")
325
    robots.write("User-agent: *\n")
326
    robots.write("Disallow: ")
327
    robots.close()
328
def internet(host="8.8.8.8", port=53, timeout=3):
329
    try:
330
        socket.setdefaulttimeout(timeout)
331
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
332
        return True
333
    except Exception as ex:
334
        return False
335
def server():
336
    global meta_input
337
    url="http://sepkjaer.pythonanywhere.com/install"
338
    headers = {'content-type': 'application/json',"NAME":meta_input,"Version":"3"}
339
    response=requests.get(url,headers=headers)
340
    #print(response)
341
def version_control():
342
    try:
343
        version_pattern=r"last_version:(.+)"
344
        if internet():
345
            response=requests.get("http://www.qpage.ir/releases.html")
346
            body=response.text
347
            last_version=float(re.findall(version_pattern,body)[0][:-3])
348
            if last_version>float(version):
349
                print("--------------------------------------------------------------------------")
350
                print("**New Version Of Qpage Is Available Now (Version "+str(last_version)+")**")
351
                print("Download Link -->"+"https://github.com/sepandhaghighi/qpage/archive/v"+str(last_version)+".zip")
352
                print("--------------------------------------------------------------------------")
353
    except:
354
        pass
355
def enter_to_exit():
356
    input("Enter any key to exit()")
357
358
def wait_func(iteration):
359
    for i in range(iteration):
360
        time.sleep(1)
361
        print(".")
362
363
364
365