Completed
Push — master ( 677c49...972db1 )
by Sepand
57s
created

address_print()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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